vba - 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”那么
如果第 1 行或 501 或 1001 等存在数据类型问题,则会引发错误(例如:错误:将 varchar 值“20v2”转换为数据类型 int 时转换失败。)但是
如果在任何其他行上存在数据类型问题,则进程说它成功,但并非所有记录都在错误行之后加载
因此,如果文件有 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
解决方案
推荐阅读
- c# - 从 C# 中的 Mixpanel API 获取数据
- java - 多线程创建多个对象,性能不佳 Java
- json - 来自 json 文件的 Ansible 循环列表
- php - 如何使用 PHP 在 razorpay 中验证付款签名?
- ios - 为什么我在 Xcode 中的一个文件消失了?
- asp.net - Paypal webhook 接收器 asp
- wordpress - the_posts_pagination 在 wordpress 主页中不起作用
- hibernate - 使用 jpa 保存实体时出现“org.hibernate.TransientObjectException:代理未与会话关联”错误
- android - 如何不在 CalendarView 中设置默认日期?
- php - 如果它与字符串匹配,则从数组中删除值 - php