0
我想按如下方法在vb.net中使用sql查詢插入數據。 name = corp int'l poc = 1在sql參數化查詢中轉義單引號
當我嘗試插入時,出現一個錯誤(「字符串後的未封閉引號」)。發生這種情況時,我試圖插入只有一個單引號的名稱。
因此,我添加了一個替換函數,用2個單引號替換1個單引號來轉義該符號。沒有錯誤,但當我看着我的數據庫,2個單引號添加,而不是1.
任何人都可以告訴我如何我可以逃脫與我的參數化查詢單引號?謝謝!
Public Function InsertData(ds As DataSet) As Boolean
Dim cmd As New SqlCommand
Dim cmd1 As New SqlCommand
Dim status As Boolean
Dim name As String
Dim poc As String
Dim id_p As New SqlParameter("id", SqlDbType.VarChar)
Dim name_p As New SqlParameter("name", SqlDbType.VarChar)
cmd.Parameters.Add(id_p)
cmd.Parameters.Add(name_p)
For i = 0 To ds.Tables(0).Rows.Count - 1
If checkExists(ds.Tables(0).Rows(i)(1).ToString(), ds.Tables(0).Rows(i)(2).ToString(), ds.Tables(0).Rows(i)(3).ToString()) = True Then
name = ds.Tables(0).Rows(i)(1).ToString()
poc = ds.Tables(0).Rows(i)(2).ToString()
If name.Contains("'") Then
name = name.Replace("'", "''")
End If
If poc.Contains("'") Then
poc = poc.Replace("'", "'")
End If
name_p.SqlValue = name
id_p.SqlValue = poc
cmd.CommandText = "INSERT INTO Code (Name,ID)" _
& " VALUES (@name,@id)"
status = ExecuteNonQuerybySQLCommand(cmd)
End If
Next
Return status
End Function
Dim strcon As String = "Data Source=x.x.x.x,1433;Network Library=DBMSSOCN;Initial Catalog=code_DB;User ID=xxx;Password=xxx;"
Public Function ExecuteNonQuerybySQLCommand(ByVal cmd As SqlCommand) As Boolean
Dim sqlcon As New SqlConnection
Dim i As Integer = 0
sqlcon.ConnectionString = strcon
cmd.Connection = sqlcon
Try
sqlcon.Open()
i = cmd.ExecuteNonQuery()
sqlcon.Close()
If i > 0 Then
Return True
Else
Return False
End If
Catch ex As Exception
Console.Write(ex)
Return False
End Try
End Function
您不需要在參數中轉義單引號。 –
...並且這個錯誤似乎不太可能來自該代碼。如果數據在DataTable中,將它拉出來在查詢中使用它似乎很奇怪 – Plutonix
問題似乎出現在您沒有向我們顯示的'ExecuteNonQuerybySQLCommand'函數中。 –