非繫結方式撰寫 SQL 陳述式時,變數若包含單引號(如 O'Brien),直接拼接字串會導致語法錯誤。本文介紹兩種解決方案(以 VB 為例)。
在執行 SQL 前呼叫此函數,將單引號加倍(' → ''):
Function ProcessStr(str As String) As String
Dim pos As Integer
pos = InStr(str, "'")
While pos > 0
str = Mid(str, 1, pos) & "'" & Mid(str, pos + 1)
pos = InStr(pos + 2, str, "'")
Wend
ProcessStr = str
End Function
缺點: 增加字串處理時間,且開發者易忘記呼叫。
使用 ADODB.Command 物件與 Parameter 集合,將含單引號的字串安全傳遞:
Dim cmd As New ADODB.Command
cmd.ActiveConnection = cn
cmd.CommandText = "SELECT * FROM Employees WHERE LastName = ?"
cmd.Parameters.Append cmd.CreateParameter("LastName", adVarChar, adParamInput, 50, "O'Brien")
Set rs = cmd.Execute
優點: 簡潔、高效、免除手動轉義、防止 SQL 注入。若搭配預存程序(預編譯),效能更佳。
ADODB.Connection,連接字串指向 pubs 資料庫。MSFlexGrid)。測試資料:Employee 表中 FNAME 欄位含 "Paolo''f"、"Paolo'f" 兩筆記錄。
UPDATE employee SET fname = 'Paolo''''f' WHERE emp_id = 'PMA42628M'
UPDATE employee SET fname = 'Paolo''f' WHERE emp_id = 'PMA42628M'
注意:SQL 字串中單引號以雙引號表示,故Paolo''f寫作'Paolo''''f'。