我试图通过使用带有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()
感谢您的帮助。
答案 0 :(得分: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()
答案 1 :(得分:2)
您只能在创建查询时使用表名(我的意思是从部分连接起来:"INSERT INTO " + foreignTable + " (data_text) VALUES...
,AFAIK),而不是查询参数。检查SqlParameterCollection.AddWithValue on MSDN以获取有关SqlCommand
参数的更多信息,还有非常好的示例。
'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#为“母语”。