I am having an issue with the SQLCommand query update handling apostrophes. I have a gridview that accepts edited text which might have apostrophes and other such accent characters.
The UPDATE keeps throwing errors on the apostrophes in the text entered causing the SQL UPDATE to fail.
Here is the code:
Dim lbl1 As Label = GridView3.Rows(e.RowIndex).Cells(0).FindControl("Label1")
IDVal = lbl1.Text
' New translation
Dim TB1 As TextBox = GridView3.Rows(e.RowIndex).Cells(0).FindControl("TextBox1")
updateString = TB1.Text
updateString = HttpUtility.HtmlAttributeEncode(updateString)
' Brief Description
Dim TB2 As TextBox = GridView3.Rows(e.RowIndex).Cells(0).FindControl("TextBox2")
newBrief = TB2.Text
If newBrief = "" Then
newBrief = DBNull.Value.ToString
Else
newBrief = TB2.Text
End If
' update the corresponding string value for Record
rootTableUpdate = "UPDATE " + userTable + " SET lang_String = '" + updateString + "', date_Changed ='" + myDate + "', prev_LangString = '" + Session("oldString") + "', brief_Descrip = '" + newBrief + "', needsTranslation = 'False', submittedBy= '" + userName + "' WHERE [Id] = " + IDVal + ";"
Dim command1 As New SqlCommand(rootTableUpdate, connection)
connection.Open()
command1.ExecuteNonQuery()
connection.Close()
The word that error’d below is actually: d'alimentation.
Incorrect syntax near ‘alimentation’.
Unclosed quotation mark after the character string ‘ WHERE [Id] = 258;’.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.Data.SqlClient.SqlException: Incorrect syntax near ‘alimentation’.
Unclosed quotation mark after the character string ‘ WHERE [Id] = 258;’.
Source Error:
Line 164: Dim command1 As New SqlCommand(rootTableUpdate, connection)
Line 165: connection.Open()
Line 166: command1.ExecuteNonQuery()
SQEE, VB.net
Your code is prone to SQL Injection.
Use Parameterized queries.
This will also prevent the issues you are having with apostrophe’s.