建立引數化命令
每次通過 ADO 連線執行的 SQL 都需要包含使用者輸入時,最好將其引數化以最大限度地減少 SQL 注入的可能性。此方法比長串聯更具可讀性,並且有助於更強大和可維護的程式碼(即通過使用返回 Parameter 陣列的函式)。
在標準 ODBC 語法中,引數在查詢文字中被賦予 ?佔位符,然後引數將按照它們在查詢中出現的順序附加到 Command。
請注意,下面的示例使用了 連線到資料來源中的 OpenDatabaseConnection 函式以簡化操作。
Public Sub UpdateTheFoos()
On Error GoTo Handler
Dim database As ADODB.Connection
Set database = OpenDatabaseConnection(SomeDSN)
If Not database Is Nothing Then
Dim update As ADODB.Command
Set update = New ADODB.Command
'Build the command to pass to the data source.
With update
.ActiveConnection = database
.CommandText = "UPDATE Table SET Foo = ? WHERE Bar = ?"
.CommandType = adCmdText
'Create the parameters.
Dim fooValue As ADODB.Parameter
Set fooValue = .CreateParameter("FooValue", adNumeric, adParamInput)
fooValue.Value = 42
Dim condition As ADODB.Parameter
Set condition = .CreateParameter("Condition", adBSTR, adParamInput)
condition.Value = "Bar"
'Add the parameters to the Command
.Parameters.Append fooValue
.Parameters.Append condition
.Execute
End With
End If
CleanExit:
If Not database Is Nothing And database.State = adStateOpen Then
database.Close
End If
Exit Sub
Handler:
Debug.Print "Error " & Err.Number & ": " & Err.Description
Resume CleanExit
End Sub
注意:上面的示例演示了引數化的 UPDATE 語句,但可以為任何 SQL 語句指定引數。