2011-11-22 119 views
0

我試圖通過使用帶有SqlConnection的參數化查詢來避免在我的字符串變量中逃脫撇號,但它不工作。任何幫助,將不勝感激。防止參數查詢逃逸撇號

更新:這是當前代碼...

'Populate Connection Object 
Dim oCnn As New SqlConnection(strConnection) 

'Define our sql query 
Dim sSQL As String = "INSERT INTO [" & foreignTable & "] (data_text) VALUES (@data_text) ; " 

'Populate Command Object 
    Dim oCmd As New SqlCommand(sSQL, oCnn) 

    'Add up the parameter, associated it with its value 

    oCmd.Parameters.AddWithValue("@data_text", data_text) 

    'Opening Connection for our DB operation 
    oCnn.Open() 

    Try 
     Dim results As Integer = oCmd.ExecuteScalar 
    Catch ex As Exception 
     LabelImport.Text &= "<font color=red>ROOT Import ERROR: " & ex.ToString & ", From Database: " & dbName & ", Text String: " & data_text & "</font><br />" 
     Throw 
    End Try 

    oCnn.Close() 
    oCmd.Parameters.Clear() 

感謝您的幫助。

回答

2

是的,那是不對的。

它應該是這樣的:

Dim sSQL As String = "INSERT INTO [" & foreignTable & "] (data_text) VALUES (@data_text);" 

和參數:

oCmd.Parameters.AddWithValue("@data_text", data_text) 

注:我不「想」就可以通過表名作爲參數。你將不得不在字符串中有表名。見Parametise table name in .Net/SQL?

另外,更改此:

Dim results As Integer = oCmd.ExecuteScalar 

Dim results as Integer = oCmd.ExecuteNonQuery() 
+0

IT現在可以工作,除了10條左右的記錄以外,還有apostrphes – htm11h

+0

@ marc11h您可以定義不適用於帶撇號的10條記錄嗎?錯誤? – LarsTech

+0

是的,給定的數量可以大得多,這是測試數據。 – htm11h

2

您只能使用表名創建查詢時(我的意思是,從部分相連來:"INSERT INTO " + foreignTable + " (data_text) VALUES...,據我所知),還不如查詢參數。有關SqlCommand參數的更多信息,請查看SqlParameterCollection.AddWithValue on MSDN,這裏也有很好的例子。

'Populate Connection Object 
Dim oCnn As New SqlConnection(strConnection) 

'Define our sql query 
Dim sSQL As String = "INSERT INTO " & foreignTable & " (data_text) VALUES (@data_text);" 

'Populate Command Object 
Dim oCmd As New SqlCommand(sSQL, oCnn) 

'Add up the parameter, associated it with its value 
oCmd.Parameters.AddWithValue("@data_text", data_text) 

'Opening Connection for our DB operation 
oCnn.Open() 

編輯:

+改爲&因爲C#作爲 「母語」。

+0

感謝您的鏈接,我會研究它。 – htm11h