2011-12-07 72 views
0

我有與SqlCommand的查詢更新處理撇號的問題。我有一個gridview接受可能有撇號和其他這樣的口音字符的編輯文本。撇號導致SQL更新失敗

更新不斷在文本撇號投擲輸入錯誤導致SQL更新失敗。

下面是代碼: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.

異常詳細信息:

System.Data.SqlClient.SqlException: Incorrect syntax near 'alimentation'.
Unclosed quotation mark after the character string ' WHERE [Id] = 258;'.

源錯誤:

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() 

是error'd下面實際上是詞

Line 164:   Dim command1 As New SqlCommand(rootTableUpdate, connection) 
Line 165:   connection.Open() 
Line 166:   command1.ExecuteNonQuery() 

SQEE,VB.net

回答

3

代碼傾向於SQL Injection

使用參數化查詢。

Dim cmd As New SqlCommand("UPDATE Table SET [email protected], [email protected]", Conn) 
cmd.Parameters.Add("@ColA", SqlDbType.Int).Value = ColA 
cmd.Parameters.Add("@ColB", SqlDbType.Int).Value = ColB 
cmd.ExecuteNonQuery() 

這也可以防止你使用撇號的問題。

+0

謝謝,如果某些值爲NULL會怎麼樣? – htm11h

+0

然後通過'DBNull.Value'作爲參數值 – Curt

+0

謝謝!!!它的工作現在。 – htm11h

2

如果parametrised調用(如@簡略的例子),而不是連接字符串:

1

更安全您應該使用參數化查詢而不是連接字符串。

這都將避免您遇到的問題,並幫助防止SQL Injection

我可以看到你正在傳遞表名,所以你必須使用dynamic SQL - 你需要通過加倍來轉義任何單個的',否則它將作爲一個字符串終止符。

你仍然需要以減輕SQL注入 - 只是加倍撇號不會在這方面有所幫助。

另外,認爲不需要動態表名或一個構建動態SQL在存儲過程中使用參數的設計,讓你至少可以進行殺毒的參數傳遞到一定程度。

+0

謝謝我會嘗試重組。 – htm11h