使Excel VBA写入SQL更快。

huangapple go评论97阅读模式
英文:

Make excel VBA write to SQL faster

问题

我有一个经过调整的VBA脚本,用于写入SQL数据库(写入约1500行)。

脚本可以运行,但需要5分钟的时间(时间太长),并导致Excel VBA显示为未响应。

有什么方法可以提高写入SQL的速度?

如何更改此脚本以更快地写入SQL?

Public Sub ConnectToDB()
    Dim DBCONT As Object
    Dim strConn As String
    Dim Database_Name As String
    Dim Table_Name As String
    Dim strSQL As String
    Dim rs As Object
    Dim LastRow As Long
    Dim i As Long
    Dim sCountry, sAsset_type, sYear, sQuarter, sinput_remaining_budget_pct_of_post_ufl_production As String

    '   设置所有变量
    Database_Name = "<数据库名称>" ' 在此处输入数据库名称
    Table_Name = "<表名称>"

    WkbName = ThisWorkbook.Name
    SheetName = "mine_ufl_input" ' 在这里定义RS所在的工作表

    '   设置SQL字符串

    ' 预备语句
    strSQL = "INSERT INTO [ufl]." & Table_Name & _
             "    ([Country], [Asset_type], [Year], [Quarter],[updated_budget_abs])" & _
             " VALUES (?, ?, ?, ?, ?)"
             
    ' 设置连接变量
    Set DBCONT = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")
    
    DBCONT.ConnectionString = "Provider=sqloledb;Server=<服务器名称>;Database=<数据库名称>;Trusted_connection=yes;"
    DBCONT.Open
    DBCONT.Execute "truncate table <表名称>"
    
    Set sh = ActiveSheet
    
    LastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
    Debug.Print LastRow
    
    For i = 2 To LastRow
        Set cmd = CreateObject("ADODB.Command")
    
        With cmd
          .ActiveConnection = DBCONT   ' 连接对象
          .CommandText = strSQL        ' SQL字符串
          .CommandType = adCmdText
    
          ' 绑定参数
          .Parameters.Append .CreateParameter("sCountryParam", adVarChar, adParamInput, 255, sh.Cells(i, 1))
          .Parameters.Append .CreateParameter("sAsset_typeParam", adVarChar, adParamInput, 255, sh.Cells(i, 2))
          .Parameters.Append .CreateParameter("sYearParam", adVarChar, adParamInput, 255, sh.Cells(i, 3))
          .Parameters.Append .CreateParameter("sQuarterParam", adVarChar, adParamInput, 255, sh.Cells(i, 4))
          .Parameters.Append .CreateParameter("supdated_budget_absParam", adVarChar, adParamInput, 255, sh.Cells(i, 17))
          '... 其他参数
    
          .Execute                     ' 运行操作
        End With
        
        Set cmd = Nothing
    Next i

    Call CloseDB

    MsgBox i & "行已导入。"

End Sub

注意:在脚本中,需要将"<数据库名称>"和"<表名称>"替换为实际的数据库名称和表名称。

英文:

I have an adapted VBA script that writes to an SQL database (writes ~1500 rows).

The script works, it takes 5min to run (too long) and causes excel vba to show up as not responding.

Any methods to improve the speed of the write to SQL would be helpful.

How would one change this script to write to SQL faster?

Public Sub ConnectToDB()
    Dim DBCONT As Object
    Dim strConn As String
    Dim Database_Name As String
    Dim Table_Name As String
    Dim strSQL As String
    Dim rs As Object
    Dim LastRow As Long
    Dim i As Long
    Dim sCountry, sAsset_type, sYear, sQuarter, sinput_remaining_budget_pct_of_post_ufl_production As String

&#39;   SET ALL VARIABLES
    Database_Name = &quot;&lt;DATABASE_NAME&gt;&quot; &#39; Enter your database name here
    Table_Name = &quot;&lt;TABLE_NAME&gt;&quot;

    WkbName = ThisWorkbook.Name
    SheetName = &quot;mine_ufl_input&quot; &#39;  WHERE RS IS

&#39;   SET SQL STRING

    &#39; PREPARED STATEMENT
    strSQL = &quot;INSERT INTO [ufl].&quot; &amp; Table_Name &amp; _
             &quot;    ([Country], [Asset_type], [Year], [Quarter],[updated_budget_abs])&quot; &amp; _
             &quot; VALUES (?, ?, ?, ?, ?)&quot;
             
    &#39;   SET TO CONNECTION VARIABLES
    Set DBCONT = CreateObject(&quot;ADODB.Connection&quot;)
    Set rs = CreateObject(&quot;ADODB.Recordset&quot;)
    
    DBCONT.ConnectionString = &quot;Provider=sqloledb;Server=&lt;SERVER_NAME&gt;;Database=&lt;DATABASE_NAME&gt;;Trusted_connection=yes;&quot;
    DBCONT.Open
    DBCONT.Execute &quot;truncate table &lt;TABLE_NAME&gt;&quot;
    
    Set sh = ActiveSheet
    
    LastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).row
    Debug.Print LastRow
    
    For i = 2 To LastRow
        Set cmd = CreateObject(&quot;ADODB.Command&quot;)
    
        With cmd
          .ActiveConnection = DBCONT   &#39; CONNECTION OBJECT
          .CommandText = strSQL        &#39; SQL STRING
          .CommandType = adCmdText
    
          &#39; BINDING PARAMETERS
          .Parameters.Append .CreateParameter(&quot;sCountryParam&quot;, adVarChar, adParamInput, 255, sh.Cells(i, 1))
          .Parameters.Append .CreateParameter(&quot;sAsset_typeParam&quot;, adVarChar, adParamInput, 255, sh.Cells(i, 2))
          .Parameters.Append .CreateParameter(&quot;sYearParam&quot;, adVarChar, adParamInput, 255, sh.Cells(i, 3))
          .Parameters.Append .CreateParameter(&quot;sQuarterParam&quot;, adVarChar, adParamInput, 255, sh.Cells(i, 4))
          .Parameters.Append .CreateParameter(&quot;supdated_budget_absParam&quot;, adVarChar, adParamInput, 255, sh.Cells(i, 17))
           &#39;... rest of parameters
    
          .Execute                     &#39; RUN ACTION
        End With
        
        Set cmd = Nothing
    Next i

    Call CloseDB

    MsgBox i &amp; &quot; Lines Imported.&quot;

End Sub

答案1

得分: 1

以下是代码部分的翻译:

Takes &lt;1 second on my local server.
英文:

Takes <1 second on my local server.

Option Explicit

Public Sub ConnectToDB()

    Dim dbName As String, tableName As String
    Dim sConn As String, dbConn As ADODB.Connection, cmd As ADODB.Command
    Dim ws As Worksheet, lastrow As Long, r As Long
    Dim t0 As Single, p As Long, SQL As String
   
    &#39;   SET ALL VARIABLES
    dbName = &quot;&lt;DATABASE_NAME&gt;&quot; &#39; Enter your database name here
    tableName = &quot;&lt;TABLENAME&gt;&quot;

    &#39;   SET SQL STRING
    SQL = &quot;INSERT INTO [ufl].&quot; &amp; tableName &amp; _
          &quot; (Country, Asset_type, Year, Quarter,updated_budget_abs)&quot; &amp; _
          &quot; VALUES (?, ?, ?, ?, ?)&quot;
             
    &#39;   SET TO CONNECTION VARIABLES
    sConn = &quot;Provider=sqloledb;Server=&lt;SERVER_NAME&gt;;&quot; &amp; _
            &quot;Database=&quot; &amp; dbName &amp; &quot;;Trusted_connection=yes;&quot;
    
    Set dbConn = New ADODB.Connection
    With dbConn
       .ConnectionString = sConn
       .Open
       .Execute &quot;TRUNCATE TABLE &quot; &amp; tableName
    End With

    &#39; PREPARED STATEMENT
    Set cmd = New ADODB.Command
    With cmd
        .ActiveConnection = dbConn
        .CommandText = SQL
        .CommandType = adCmdText
        .Prepared = True        
        &#39; BINDING PARAMETERS
        For p = 0 To 4
            .Parameters.Append .CreateParameter(&quot;P&quot; &amp; p, adVarChar, adParamInput, 255)
        Next
    End With

    Dim arFields: arFields = Array(1, 2, 3, 4, 17) &#39; columns
    t0 = Timer
    
    &#39; INSERT RECORDS
    Set ws = ActiveSheet &#39; or Thisworkbook.sheets(&quot;&quot;mine_ufl_input&quot;)
    With ws
        lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
        dbConn.Execute &quot;BEGIN TRANSACTION&quot;
        For r = 2 To lastrow
            For p = 0 To 4
                cmd.Parameters(p).Value = .Cells(r, arFields(p))
            Next
            cmd.Execute &#39; RUN ACTION
        Next
        dbConn.Execute &quot;COMMIT TRANSACTION&quot;
    End With

    &#39;Call CloseDB
    MsgBox lastrow - 1 &amp; &quot; Lines Imported.&quot;, _
           vbInformation, Format(Timer - t0, &quot;0.0 secs&quot;)

End Sub


</details>



huangapple
  • 本文由 发表于 2023年3月12日 17:09:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75712081.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定