使用绑定变量将数据上传到 SQL 的 ADODB 连接

ADODB Connection to upload data to SQL using bind variables

我正在尝试将一些数据从电子表格上传到 SQL 数据库。我使用 here 中的代码作为基础,必须制作一些模组才能使其正常工作。

Sub newtest()

Dim conn As ADODB.Connection
Dim cmd As New ADODB.Command
Dim cs As String
Dim C1, C2, C3, C4 As String
Dim RowNo As Long
    Dim wbk As Workbook
    Dim strFile As Variant
    Dim shtname As String
    ChDir "xxxxxx"
    strFile = Application.GetOpenFilename
    If strFile = False Then
    Exit Sub
    Else: End If

    Application.ScreenUpdating = False


Set conn = New ADODB.Connection

cs = "Provider=SQLOLEDB;Data Source=xxxxx;Initial Catalog=xxxx;User ID=xxx; Password=xxxxxx; "

conn.ConnectionString = cs

conn.Open


' *** Open workbooks first ***
Set wbk = Workbooks.Open(strFile)
shtname = ActiveWorkbook.Worksheets(1).Name
lastrow = wbk.Sheets(1).Cells(Rows.Count, "A").End(xlUp).Row + 1
With Sheets(shtname)

cmd.ActiveConnection = conn
cmd.CommandText = "insert into EcommerceXRefMapping_C_Copy values (@EquivalentPartNumber_C, @Manufacturer_C, @CatamacPartNumber_C, @Notes_C)"
cmd.NamedParameters = True

 'Skip the header row
        RowNo = 2

        'Loop until empty cell in Col 1
        Do Until .Cells(RowNo, 1) = ""
            i = i + 1
            C1 = .Cells(RowNo, 1)
            C2 = .Cells(RowNo, 2)
            C3 = .Cells(RowNo, 3)
            C4 = .Cells(RowNo, 4)

            'Generate and execute sql statement to import the excel rows to SQL Server table

            cmd.Parameters.Append cmd.CreateParameter("@EquivalentPartNumber_C", adVarChar, adParamInput, 256, C1)
            cmd.Parameters.Append cmd.CreateParameter("@Manufacturer_C", adVarChar, adParamInput, 256, C2)
            cmd.Parameters.Append cmd.CreateParameter("@CatamacPartNumber_C", adVarChar, adParamInput, 256, C3)
            cmd.Parameters.Append cmd.CreateParameter("@Notes_C", adVarChar, adParamInput, 256, C4)

            cmd.Execute

            RowNo = RowNo + 1
        Loop

End With

        wbk.Close
        Application.ScreenUpdating = True

End Sub

我在尝试执行时遇到错误

cmd.execute

错误信息是

Run-time error'-2147217800 (80040e14)':
Must declare the scalar variable "@EquivalentPartNumber_C".

有什么解决办法吗?我以为变量的声明是用“@”字符完成的?抱歉,我是 VBA 的新手,所以请多多包涵。

谢谢!

在我看来,您将 stored proceduretext 类型的命令混合使用,但是...

  1. 传参时可以省略@
  2. 您应该在 cmdCommandText 行之后添加 cmd.CommandType = adCmdText
  3. 我会将 SQL 查询更改为:

"insert into EcommerceXRefMapping_C_Copy values (?, ?, ?, ?)"

然后以这种方式传递参数(正确的顺序很重要):

cmd.Parameters(0) = c1
cmd.Parameters(1) = c2
cmd.Parameters(2) = c3
cmd.Parameters(3) = c4