How can I insert a single quote (') in sql? - sql

I got some strings that contains a single quote (') like Mayor's Office:
Dim Str = "Insert into EntryTbl(Office, DateCreated, TimeCreated)" & _
"Values('" & OfficeBox.Text & "', " & _
" '" & Now.ToShortDateString & "', " & _
" '" & Now.ToString("HH:mm:ss") & "')"
and the officebox.text contains a string Mayor's Office
Glad for any help :)

IMO, parametrized query is better because it prevents SQL injection and it will handle escaping for you(no need to write additional method to handle escaping)
Dim cmd As New SqlCommand("", Conn())
With cmd
.CommandText = "Insert into tbl(Office, DateCreated, TimeCreated)" & _
"Values(#office,#DateCreated,#TimeCreated)"
.Parameters.AddWithValue("#office", OfficeBox.Text)
.Parameters.AddWithValue("#DateCreated", Now.ToShortDateString)
.Parameters.AddWithValue("#TimeCreated", Now.ToString("HH:mm:ss"))
.ExecuteNonQuery()
End With
Take a look at How do I create a parameterized SQL query? Why Should I? for more informations

The built in solution is to use
QUOTENAME(#string)
function to put the quotes.

Related

number of query values and destination fields not the same

hello I'm looking to just do a simple reason for what this is not working ... i have tried adding the same column twice, taking out the TextBox2 i just cant get it to work. all that works is if i take the last value out and the last column otherwise it will not work at all and i have now idea why.what i want is it to place a check mark in there to along with the name.
code:
Dim SqlText As String = "INSERT INTO tblEmployeeNames ([EmployeeName],
[UseForDropDown]) VALUES ('" & Trim(TextBox1.Text) & " " &
Trim(TextBox2.Text) & " " & (CheckBox1.Checked) & "')"
You have included the checkbox-state with the first value, you need to separate them with a comma.
Dim SqlText As String = "INSERT INTO tblEmployeeNames ([EmployeeName], [UseForDropDown]) VALUES ('" & Trim(TextBox1.Text) & " " & Trim(TextBox2.Text) & "', " & (CheckBox1.Checked))"
Notice the Checked state doesn't require apostrophes around it.
See SLaks comment as well, you should be using parameterized queries.

Error in my vb but correct in my sql query

Error in my vb but correct in my sql query. Can somebody can correct my VB code.
This is my wrong code in VB
cmd = New Odbc.OdbcCommand("SELECT * FROM tblvendorpartnumber WHERE vendorpnumber ='" & Trim(TextBox11.Text.TrimEnd()) & " OR vendorpnumber ='" & Trim(TextBox2.Text.TrimEnd()) & "'", con)
This is my correct code in mysql query
SELECT *
FROM pcba_info.tblvendorpartnumber
WHERE partnumber = '' or vendorpnumber = '';
You must resolved the problem in SQL injections to
You forgot to include the pair of other single quote.
From
TextBox11.Text.TrimEnd()) & " OR
To
Trim(TextBox11.Text.TrimEnd()) & "' OR
To form as
cmd = New Odbc.OdbcCommand("SELECT * FROM tblvendorpartnumber WHERE vendorpnumber ='" & TextBox11.Text.Trim().Replace("'", "''") & "' OR vendorpnumber ='" & TextBox2.Text.Trim().Replace("'", "''") & "'", con)
You need to avoid mixing the VB string functions with those of SQL. Write the entire query inside quotes to be certain will work in SQL.
Try like this
Trim will trim any leading or trailing blank spaces from a string. So if the string was " Text", then Trim would delete those spaces for you, leaving just "Text".
Dim S1,S2 as String
S1 = TextBox11.Text
S2 = TextBox12.Text
cmd = New Odbc.OdbcCommand("SELECT * FROM tblvendorpartnumber WHERE vendorpnumber ='" & S1.Trim & " OR vendorpnumber ='" & S2.Trim & "'", con)

VB.net Access Update Query

VB.net access update query is giving a Syntax Error in Update Query Error. My query is as follows:
query = "UPDATE users SET username='" & newUsername & "', password='" & newPassword & "', department='" & newDepartment & "', display_name='" & newDisplayName & "', email='" & newEmail & "', extension='" & newExtension & "', access_level='" & newAccessLevel & "' WHERE id=" & usrID
None of the above variables have any symbols at all. What am I doing wrong?
::UPDATE::
UPDATE users SET username='alison', password='farm1234',department='1',display_name='Alison *****', email='production#**********.com', extension='1012',access_level='50' WHERE id=1
This is what the query runs as.
The error is caused by the usage of the reserved keyword PASSWORD without enclosing it in square brackets.
Said that, you never use string concatenation to build sql commands, but always a parameterized query to avoid Sql Injection problems but also syntax error in parsing text values (containing single quotes) or decimal values with their decimal separators or dates values.
So, a possible approach to your task could be
query = "UPDATE users SET username=?, [password]=?, department=?, " & _
"display_name=?, email=?, extension=?, access_level=?" & _
" WHERE id=?"
Using cmd = new OleDbCommand(query, connection)
cmd.Parameters.AddWithValue("#p1", newUsername)
cmd.Parameters.AddWithValue("#p2", newPassword)
cmd.Parameters.AddWithValue("#p3", newDepartment)
cmd.Parameters.AddWithValue("#p4", newDisplayName)
cmd.Parameters.AddWithValue("#p5", newEmail)
cmd.Parameters.AddWithValue("#p6", newExtension)
cmd.Parameters.AddWithValue("#p7", newAccessLevel)
cmd.Parameters.AddWithValue("#p8", usrID)
cmd.ExecuteNonQuery()
End Using
Keep in mind that OleDb doesn't use the parameter names to find the corresponding placeholder in sql command text. Instead it uses a positional progression and thus adding the parameters to the collection should respect the order in which the parameter appears in the sql command text
ConStr()
Qry="UPDATE users SET username=#uname, [password]=#pass, department=#dept, " & _
"display_name=#dnam, email=#email, extension=#ext, access_level=#acslvl" & _
" WHERE id=#id"
cmd = new oledbcommand(Qry,Conn)
cmd.Parameters.AddWithValue("#uname",newUsername)
cmd.Parameters.AddWithValue("#pass",newPassword)
cmd.Parameters.AddWithValue("#dept",newDepartment)
cmd.Parameters.AddWithValue("#dnam",newDisplayName)
cmd.Parameters.AddWithValue("#email",newEmail)
cmd.Parameters.AddWithValue("#ext",newExtension)
cmd.Parameters.AddWithValue("#acslvl",newAccessLevel)
cmd.Parameters.AddWithValue("#id",usrID)
cmd.ExecuteNonQuery()

SQL command will not insert into database

I'm trying to use a VB button to insert data into a database, but it keeps bringing up the error message I have in place for exceptions.
Can anyone help me with why this does not update the database?
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sql As String
Dim adapter As New SqlDataAdapter
Dim Customer As String = TextBox1.Text
Dim Product As String = TextBox2.Text
Dim Location As String = TextBox3.Text
Dim Details As String = TextBox4.Text
Dim Owners As String = DropDownList1.Text
Dim Urgency As String = DropDownList2.Text
connetionString = "Data Source=ZUK55APP02;Initial Catalog=BugFixPortal;User ID=SLC***;Password=rep***"
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand
adapter.UpdateCommand.CommandText = sql
adapter.UpdateCommand.ExecuteNonQuery()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
End Sub
I would not go down this road as your code is weak against SQL Injection
you should use parameters instead.Something like the below
c.Open();
string insertString = #"insert into YourTable(name, street, city,....) values(#par1, #par2, #parN,....)"
SqlCommand cmd = new SqlCeCommand(insertString, c);
cmd.Parameters.Add("#par1", SqlDbType.VarChar).Value = "MyName";
//etc
cmd.ExecuteNonQuery();
c.Close();
You are incorrectly quoting your values.
This string has an opening and closing single quote around ALL the values, which is incorrect.
VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
Instead, put single quotes around character data, eg., if Product is a varchar, it would look like this:
VALUES (" & Owners & ", " & Customer & ", '" & Product & "', " & Location & ", " & Urgency & ", " & Details & ")"
The real problem, though, is that you should be using parameterized queries instead. This code is prone to SQL injection attacks.
Change this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
to Something like this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!" & ex.Message)
It will give you more details on the exception, however at a quick glance I can see a problem, the values you are trying to insert are strings, you've enclosed all your values in a single set of ' characters, rather than enclosing each string parameter in a pair of ' values, i.e.
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & "', '" & Customer & "', '" & Product & "',' " & Location & "', '" & Urgency & "', '" & Details & "')"
You really should look at parameterizing your queries as you're wide open to SQL injection attacks. See HERE
In terms of your code itself, your SQL syntax is wrong as you need to put apostrophes around each value. Try this:
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('" & Owners & "', '" & Customer & "', '" & Product &
"', '" & Location & "', '" & Urgency & "', '" & Details & "')"
Here's an example using Parameters
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('#Owners', '#Customer', '#Product', '#Location', '#Urgency', '#Details')"
Then add parameters like so:
command.Parameters.AddWithValue("#Owners", Owners)
command.Parameters.AddWithValue("#Customer", Customer)
command.Parameters.AddWithValue("#Product", Product)
command.Parameters.AddWithValue("#Location", Location)
command.Parameters.AddWithValue("#Urgency", Urgency)
command.Parameters.AddWithValue("#Details", Details)
I think you want to use adapter.InsertCommand instead of adapter.UpdateCommand
in
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand //(adapter.InsertCommand)
adapter.UpdateCommand.CommandText = sql //(adapter.InsertCommand)
adapter.UpdateCommand.ExecuteNonQuery() //(adapter.InsertCommand)
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
and agree with parametrized sql query
see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx for more infos

converting html symbol code before sql insert stmt

I am trying to export some data from a SQL Express table to Access using VB.net. The data is correctly displayed in SQL as, for example, temperature with the small degree object and the letters F or C for Farenhiet or Celsius. The character is of course represented by ° = "&#176" in html code, which is what appears in my access tables.
How can I get the insert statements to correctly pass this symbol? I have thousands of records and this applies to maybe a hundred or so in each of a few hundred DB's I am running this conversion on.
I read the data from a Gridview an .aspx .net web page and then use an insert query with an Access OLEDB connection.
SQLString1 = "INSERT INTO tblFornStrings (Str_ID, Code, Str_Name, Srt_Text, Lng_Text, Alt_Text) "
SQLString1 = SQLString1 & "VALUES ('" & StrngID & "', "
SQLString1 = SQLString1 & "'" & Code & "',"
SQLString1 = SQLString1 & "'" & Str_Name & "',"
SQLString1 = SQLString1 & "'" & newText1 & "',"
SQLString1 = SQLString1 & "'" & newText2 & "',"
SQLString1 = SQLString1 & "'" & newText3 & "')"
' SQLString1 = SQLString1 & "'" & tblSource & "')"
Dim dbCommand1 = New OleDbCommand(SQLString1, pConn)
pConn.Open()
dbCommand1.ExecuteNonQuery()
dbCommand1 = Nothing
These are the two fields that have the data, newText1 = Srt_Text, newText2 = Lng_Text
I have now tried to make this a parameterized query, having read that it would allow the string to be copied without an encoding issue. It did not work. Here is another version of the INSERT code using the parameters.
Dim SqlString As String = "INSERT INTO Strings (Str_ID, Code, Str_Name, Srt_Text, Lng_Text, Alt_Text) Values (?,?,?,?,?,?)"
Using cmd As New OleDbCommand(SqlString, pConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("Str_ID", StrngID)
cmd.Parameters.AddWithValue("Code", Code)
cmd.Parameters.AddWithValue("Str_Name", Str_Name)
cmd.Parameters.AddWithValue("Srt_Text", newText1)
cmd.Parameters.AddWithValue("Lng_Text", newText2)
cmd.Parameters.AddWithValue("Alt_Text", newText3)
pConn.Open()
cmd.ExecuteNonQuery()
pConn.Close()
End Using
The output is the same as is dispalyed in the graphic for the output of the first code block.
Thanks for any suggestions.
So you have some strings extracted from Gridview, and so far you were using those strings "as is" to build SQL statements (or to set parameter values for a parameterized database command). Now, what happens if, instead of using them "as is" you'd decode them first - e.g. by passing them to HttpUtility.HtmlDecode(...) method? (See this MSDN page for more details.)