从VBA字典提高对Access DB的多次插入的速度

时间:2019-01-02 05:58:01

标签: sql vba ms-access adodb

我正在尝试获取VBA词典,并且可以:

  • 如果新行不存在,请将其插入数据库中
  • 更新行

虽然我当前的代码可用于此目的,但是对于我可能需要更新的成千上万条记录而言,它的运行速度非常慢,而我在此站点上发现的其他解决方案并不能真正实现我的追求。谁能帮助我实现这一目标?到目前为止,我的代码如下:

Sub UpdateDatabase(dict As Object)
Dim Conn As Object, StrSQL As String, Rs As Object
Dim hmm As ADODB.Recordset

Set Conn = CreateObject("ADODB.Connection")
Conn.Provider = "Microsoft.ACE.OLEDB.12.0"
Conn.Open "C:\XXXX\cfrv2.accdb" 

dictCount = dict.Count
counter = 0
For Each varKey In dict.Keys()
    Application.StatusBar = Str(counter) & "/" & Str(dictCount)
    counter = counter + 1
    StrSQL = "SELECT * FROM `All SAMs Backlog` WHERE [LOCID] = '" & varKey & "'"

    Set hmm = Conn.Execute(StrSQL)
    If hmm.BOF And hmm.EOF Then
        StrSQL = "INSERT INTO `ALL SAMs Backlog` ([SAM], [LOCID], [RTC Date], [CFR Status], [CFR Completed Date], [CFR On Hold Reason], [MDU], [ICWB Issue], [Obsolete]) VALUES (dict.Item(varKey)(0), '" & varKey & "', '20/12/2018', '" & dict.Item(varKey)(1) & "', '02/01/2019', '" & dict.Item(varKey)(2) & "' , '" & dict.Item(varKey)(3) & "' , '" &dict.Item(varKey)(4) & "' , '" & dict.Item(varKey)(5) & "')"
        Conn.Execute (StrSQL)
    Else
        'Update the LOC in the table
        StrSQL = "UPDATE `All SAMs Backlog` SET ([CFR Status] = '" & dict.Item(varKey)(1) & "', [CFR On Hold Reason] = '" & dict.Item(varKey)(2) & "', [MDU] = '" & dict.Item(varKey)(3) & "', [ICWB Issue] = '" & dict.Item(varKey)(4) & "', [Obsolete] = '" & dict.Item(varKey)(5) & "')"
        Conn.Execute (StrSQL)
    End If
Next

Conn.Close
End Sub

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

要么:

将字典的内容写到临时表中,然后按以下说明运行查询:

Update or insert data in table

或:

打开[All SAMs Backlog]作为记录集,根据需要将字典循环到 add edit 记录,然后关闭记录集。