首页 > 解决方案 > VBA ADODB 多个插入语句不引发错误

问题描述

希望有人可以帮助我解决以下问题。我正在尝试将 csv 文件加载到 SQL db 中,我首先将其导入到 Excel 中的 aw/s 中。然后我使用导入的记录来构建我的插入语句,使用 Dick Kusleika 在他的帖子Bulk insert into sql from an array in VBA 中的建议

然后,我添加了 Juan Carlos Oropeza 的建议,即从此处一次插入 n 条记录 有什么方法可以提高此 VBA 循环将数据插入 SQL 的速度?

性能非常好,如果记录没有问题,整个文件都会被加载。

但问题是当我遇到数据类型问题时,我遇到了麻烦

如果我设置“i mod 500”那么

因此,如果文件有 608 行并且 mod 设置为 100(i mod 100)并且错误出现在第 365 行,那么 36 条记录不会被加载,并且第 400 行之后的记录会被加载。

不知道我在这里做错了什么

任何帮助将不胜感激。

谢谢

Sub Build_Stmt_Load_Data()
    Dim vaData As Variant
    Dim i As Long, j As Long
    Dim aReturn() As String
    Dim aCols() As String
    Dim aVals() As Variant
    Dim con As New ADODB.Connection
    Dim rs As New ADODB.Recordset
   
On Error GoTo err    

'Define the insert statement
    sInsert = "INSERT INTO " & fulltablename
    sVal = " VALUES "    
            
'Establish connection to the database
If con.State <> 1 Then
    con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"
End If

Set rs.ActiveConnection = con

'Get rows to be loaded into an array
 With ThisWorkbook.Sheets("Sheet1") 
     
 Set datarange = .UsedRange 

    vaData = datarange.Value
    ReDim aReturn(1 To UBound(vaData))
    ReDim aCols(1 To UBound(headData, 2))
    ReDim aVals(1 To UBound(vaData, 2))
    
     'Fill column name array from first row
    For j = LBound(headData, 2) To UBound(headData, 2)
        aCols(j) = headData(1, j)
    Next j
      
    'Go through the rest of the rows
    For i = LBound(vaData, 1) To UBound(vaData, 1)

        'Fill a temporary array
        For j = LBound(vaData, 2) To UBound(vaData, 2)
            aVals(j) = Replace$(vaData(i, j), "'", "''")
        Next j

        'Build the string into the main array
       aReturn(i) = sINSERT & "(" & Join(aCols, ",") & ")" & sVAL & "('" & Join(aVals, "','") & "');"
         
          If i <= lastRow Then
    
        InsertStmt = InsertStmt & aReturn(i) & vbCrLf
   
             If i Mod 500 = 0 Then
              con.Execute(InsertStmt)
                InsertStmt = vbNullString
             End If        
        End If
        
    Next i    
        If InsertStmt <> vbNullString Then
            con.Execute(InsertStmt)
        End If      
            con.Close
            Set con = Nothing
End with

 Exit Sub
 
err:       
    MsgBox (Error(err)), 48, "Error"

End Sub

标签: vbaadodb

解决方案


推荐阅读