Excel VBA MySql参数化更新“无效参数类型”

时间:2019-06-25 14:29:42

标签: mysql excel vba adodb

我正在创建一个界面,用户可以在其中使用excel来无缝更改SQL数据库。我可以很好地检索数据,但是在更新记录时,我得到的是“无效的参数类型”。

仅将值连接到查询中就可以正常工作,但是为了防止SQL注入,我需要一个参数化查询。我尝试用ADO数据类型替换该值,但是这并没有改变任何内容。我尝试了未命名的参数,这些参数始终向数据库提交值16而不是所需的字符串值

Private Sub Worksheet_Change(ByVal Target As Range)
        ID = Cells(Target.Row, 1).Value
        Dim locValue As String
        locValue = Cells(Target.Row, 2).Value

        Dim Cm As ADODB.Command
        Set Cm = New ADODB.Command

        Cm.NamedParameters = True
        Cm.CommandText = "UPDATE issues SET " _
        & "location = @location " _
        & "WHERE id = " & ID

        Dim locationParameter As ADODB.Parameter

        Set locationParameter = Cm.CreateParameter("@location", adVarChar, adParamInput, 255)
        Cm.Parameters.Append locationParameter
        locationParameter.Value = locValue

        SqlConnection(Cm)
End Sub

(我知道ID尚未参数化,问题出在位置)

Public Function SqlConnection(Cm As ADODB.Command) As ADODB.Recordset
 Dim Cn As ADODB.Connection
    Dim Server_Name As String
    Dim Database_Name As String
    Dim User_ID As String
    Dim Password As String
    Dim SQLStr As String

    Server_Name = "127.0.0.1" ' Enter your server name here
    Database_Name = "issues_and_outages" ' Enter your  database name here
    User_ID = "root" ' enter your user ID here
    Password = "password" ' Enter your password here

    Set Cn = New ADODB.Connection
    Cn.Open "Driver={MySQL ODBC 8.0 ANSI Driver};Server=" & Server_Name & ";Database=" & Database_Name & _
    ";Uid=" & User_ID & ";Pwd=" & Password & ";"

    Cm.CommandType = adCmdText
    Cm.ActiveConnection = Cn

    Set SqlConnection = Cm.Execute

End Function

该服务器是具有issue_and_outages表的MySQL,其列包含:

  • id(整数,无符号,密钥,自动递增)

  • 位置(varchar(255),可为空)

更新单元格时,应该更新位置列,错误为

“运行时错误'-2147217887(80040e21)”: [MySQL] [ODBC 8.0(a)驱动程序] [mysqld-8.0.16]无效的参数类型“

给出

,在Cm.Execute行上有错误。但是,数据库具有一列类型为varchar的大小为255的列,该列应为adVarChar,因此我不希望出现错误。

1 个答案:

答案 0 :(得分:0)

正如对此SO answer进行的常规讨论和总结一样,大多数提供程序/驱动程序的ADO API不支持非存储过程SQL语句的命名参数。而是使用qmark位置参数样式。

Set Cm = New ADODB.Command

With Cm
    .ActiveConnection = Cn
    .CommandType = adCmdText
    .CommandText = "UPDATE issues SET location = ? WHERE id = ?"

    .Parameters.Append .CreateParameter("loc_param", adVarChar, adParamInput, 255, locValue)
    .Parameters.Append .CreateParameter("id_param", adInteger, adParamInput,, ID)

    .Execute
End With