VBA 创建参数化命令

示例

每当通过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 Anddatabase.State= adStateOpen Then
        database.Close
    End If
    Exit Sub
Handler:
   Debug.Print"Error " &Err.Number& ": " & Err.Description
    Resume CleanExit
End Sub

注意:上面的示例演示了参数化的UPDATE语句,但是可以为任何SQL语句提供参数。