How to ignore special symbols in SQL? - sql

I want to get this sentence stored in SQL.
"WorkForceNow (WFN): Production: DS work for new schema on Training Farm"
My Insertion Code :
Dim sqq, sqq1 As New SqlConnection
sqq.ConnectionString = "##Conection string##"
sqq.Open()
Dim sqq2 As String = "Insert into [Reviews] values('" & TextBox1.Text & "')"
Dim cmd1 As New SqlCommand(sqq2, sqq)
cmd1.ExecuteNonQuery()
sqq.Close()
Error :
String or binary data would be truncated. The statement has been
terminated.
How to ignore special symbols in SQL?

Related

Building an odbc command string in Visual Basic

I'm trying to figure out where I am going wrong with the following SQL string in VB.NET
Dim SQL As String = "INSERT INTO USERS (" & String.Join(",", PropertyNames) & ", auditmonth) VALUES ('" & String.Join("','", Values) & "',", MonthName & "'"))
I'm getting the following three errors:
End of statement expected
Variable 'MonthName' hides a variable in an enclosing block
Unused local variable 'MonthName'
If I change back to
Dim SQL As String = "INSERT INTO USERS (" & String.Join(",", PropertyNames) VALUES ('" & String.Join("','", Values) & "')"
Then everything works fine. But what I'm trying to do is just add the current month to the database entry. The variable MonthName gets populated successfully. I'm just screwing something up with the syntax of the SQL command.
You should try breaking it up to multiple lines, and debug it to review the whole string constructed:
"INSERT INTO USERS (" &
String.Join(",", PropertyNames) &
", auditmonth) VALUES ('" &
String.Join("','", Values) & "','" &
MonthName & "')"
If your VB.NET compiler supports it, use this string substitution syntax for better readability:
String.Format(
"INSERT INTO USERS ({0}, auditmonth) VALUES ('{1}','{2}')",
String.Join(",", PropertyNames),
String.Join("','", Values),
MonthName)
and, do as #vku says!
You really should use SQL parameters to pass the values. If you try to concatenate them in a string, it will break if there is an apostrophe in the value, and it's also vulnerable to SQL injection attacks.
As shown in tinamzu's answer, it is better to spread the code out over several lines to make it easier to read. Also, use as many variables as you like to keep each line simple.
So, you might have something like this:
Dim columnNames = String.Join(",", propertyNames)
Dim valuePlaceholders = String.Join(", ", Enumerable.Repeat("?", values.Count))
Dim sql = String.Format("INSERT INTO USERS ({0}, auditmonth) VALUES ({1}, ?)",
columnNames,
valuePlaceholders)
Using conn As New OleDbConnection("yourConnectionString"),
cmd As New OleDbCommand(sql, conn)
For Each v In values
cmd.Parameters.Add("?", OleDbType.VarChar).Value = v
Next
cmd.Parameters.Add("?", OleDbType.VarChar).Value = monthName
conn.Open()
cmd.ExecuteNonQuery()
End Using
(Change the OleDbType.VarChar to match the relevant database column types.)
If you are using version 2015 or later of Visual Studio, you could use:
Dim sql = $"INSERT INTO USERS ({columnNames}, auditmonth) VALUES ({valuePlaceholders}, ?)"
instead as it is clear using just one line.

Visual Studio Vb.net loaded dataset from oracle query missing or replacing first row of data

I have a vb.net application program that is suppose to query a oracle/labdaq database and load the dataset into a datatable. For some reason the query works fine and there is no exception thrown, however, when I load the data it seems to be missing the first row. I first noticed the issue when I did a query for a single row and it returned zero rows when I checked the datatable's row amount during debugging. I then compared all my data sets to a data miner application straight from the oracle source and i seems to always be missing one, the first, row of data when I use the application.
here is the code... I changed the query string to something else to maintain company privacy
Private Sub CaqOnSQL(strFileDirect As String)
Try
Dim connString As String = ConfigurationManager.ConnectionStrings("CA_Requisition_Attachments.Internal.ConnectionString").ConnectionString
Dim conn As New OracleConnection With {
.ConnectionString = connString
}
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
conn.Open()
Dim Cmd As New OracleCommand(strQuerySQL, conn) With {
.CommandType = CommandType.Text
}
Dim dr As OracleDataReader = Cmd.ExecuteReader()
dr.read()
Dim dt As New DataTable
dt.TableName = "RESULTS"
dt.Load(dr)
ExcelFileCreation(dt, strFileDirect)
You should remove the line:
dr.read()
The call to Read is what is causing you to skip the first row, when combined with the DataTable Load method.
In addition, I have taken the liberty to make some additional changes to your code for the purposes of Good Practice. When using Database objects like Connection and Command, you should wrap them in Using blocks to ensure the resources are released as soon as possible.
Dim dt As New DataTable()
dt.TableName = "RESULTS"
Using conn As New OracleConnection(connString)
conn.Open()
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
Using command = New OracleCommand(strQuerySQL , conn)
Using dataReader = command.ExecuteReader()
dt.Load(dataReader)
End Using
End Using
End Using
Note: Be wary of Using blocks when using a DataReaderas you may find the connection is closed when you don't want it to be. In this case, the DataReader is used entirely within this function and is safe to use.

Checking access database vb.net

I am trying to compare the values in my dictionary which contains values/quantities to a standard database containing similar values/quantities. I want to check if the value matches the database, then check if the quantity is less than the database.
I keep getting an error when I run the code on the "Using myreader" line, with the following: System.Data.OleDb.OleDbException: 'IErrorInfo.GetDescription failed with E_FAIL(0x80004005).' This is my first time using OleDBDatareader so perhaps I am doing something incorrectly. Is this not allowed, I assumed comparing a list a values in a dictionary should be possible.
Dim myconnection As OleDbConnection
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\UsersTables.accdb; Persist Security Info=False"
myconnection = New OleDbConnection(constring)
myconnection.Open()
Dim keepSell As String
For Each KeyPair In colSums
Dim sqlQry As String
sqlQry = "SELECT Part,Quantity FROM PartsList WHERE Item = '" & keyPair.Key & "'AND Size= '" & keyPair.Value & "'"
Dim cmd As New OleDbCommand(sqlQry, myconnection)
Using myreader As OleDbDataReader = cmd.ExecuteReader()
If myreader.Read() Then
keepSell = "Keep"
Else
keepSell= "Sell"
End If
'myreader.Close()
End Using
DataGridView1.Rows.Add(KeyPair.Key, KeyPair.Value, keepSell)
Next

VB - Using data held within a textbox to update a table

How do you use SQL to put data into an empty table? So far in my code I have taken the data from an SQL table and then have put it into a Text Box using the following code:
Dim query As String = "SELECT Pronunciation, Character FROM [Katakana List] WHERE Pronunciation='" & pronunciation & "';"
Dim instruction = New SqlCommand(query, sqlCon)
Dim da As New SqlDataAdapter
da.SelectCommand = instruction
da.Fill(Katakana)
Textbox1.text=DT.row(0)("column")
Now that the data is held in the text box, how would I do the reverse of this process to put the data into an empty table. It would help if someone could give me an example of the query I could use to put the data back in.
If you want update data which you get from query before, then use UPDATE-query
If you want insert brand new data then use INSERT - query
'For updating existing data
Dim query As String = "UPDATE [Katakana List] SET Character = #NewCharacter WHERE Pronunciation=#Pronunciation"
'For Inserting new data
Dim query As String = "INSERT INTO [Katakana List] (Character) VALUES (#NewCharacter);"
Using instruction As New SqlCommand(query, sqlCon)
'Better practice to use parameters in query
instruction.Parameters.AddWithValue("#Pronunciation", pronunciation)
instruction.Parameters.AddWithValue("#NewCharacter", Textbox1.text)
instruction.ExecuteNonQuery()
End Using
If you want to set the data in the textbox into datatable just do it like this :
DT.row(0)("column") = Textbox1.text
if you want to enter it into database create query to do so , something like this :
Dim query As String = "Insert Into TableName(col1) Values('"& Textbox1.text &"');"
Dim command = New SqlCommand(query, sqlCon)
command.ExecuteNonQuery()

how to insert a row to my db table from vb.net

am using vb.net, and i want to insert a row to my db Table "adwPays" from my windows form.
this is my code:
Dim CC, EngName, FreName, LanCode As String
Dim DialCode As Integer
CC = txtCC.Text
EngName = txtEN.Text
FreName = txtFN.Text
LanCode = txtLC.Text
DialCode = txtDC.Text
Dim MyConn As New SqlConnection("Server=(local);Database=dbAjout;Integrated Security=True")
Dim query As String
query = "INSERT INTO adwPays (CC, Anglais,Francais,CodeLangue,IndicInter) VALUES ( ' " & CC & "','" & EngName & "','" & FreName & "','" & LanCode & "','" & DialCode & " ');"
Dim cmd As New SqlCommand(query, MyConn)
MyConn.Open()
cmd.ExecuteScalar()
MyConn.Close()
BUT its giving me this error
"An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: String or binary data would be truncated.
The statement has been terminated."
any help?
Use a parameterized query like this
Dim query = "INSERT INTO adwPays (CC, Anglais,Francais,CodeLangue,IndicInter) " &
"VALUES (#cc, #ename, #fname, #lan, #dial)"
Using MyConn = New SqlConnection("Server=(local);Database=dbAjout;Integrated Security=True")
Using cmd = New SqlCommand(query, MyConn)
cmd.Parameters.AddWithValue("#cc", CC)
cmd.Parameters.AddWithValue("#ename", EngName)
cmd.Parameters.AddWithValue("#fname", FreName)
cmd.Parameters.AddWithValue("#lan", LanCode)
cmd.Parameters.AddWithValue("#dial", DialCode)
MyConn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Using a parameterized query allows to avoid problems with Sql Injections and clears the command text from the formatting quotes around strings and dates and also let the framework code pass the correct decimal point for the numeric types when need
I have also added a Using Statement around the SqlConnection and the SqlCommand to be sure that the objects are closed and destroyed. The parameters are all passed as strings, this could be wrong if any of your database fields are not of text type.
It sounds like you have a String value that is longer than the database type size allows. Can you verify the type and size of each of the following fields:
cc
ename
fname
lan
Now cross-reference those sizes with what the values are in the textbox fields you are pulling them from in the UI.
My money is on one of those exceeding the database size limits.
If that is the case, then you need to introduce length checking before you attempt to save to the database.