【问题标题】:Overflow when looping through SQL-inserts for an ADODB.connection循环遍历 ADODB.connection 的 SQL 插入时溢出
【发布时间】:2022-01-27 12:14:15
【问题描述】:

我正在尝试找出一种快速、自动化的方法,将金融服务提供商的一些实时日期插入到 Excel 中,这只能通过大约 100,000 个值的块中的 excel 插件来获取。 目前我正在使用下面的代码,到目前为止它似乎按预期工作:

Sub insert()

'Declare Variables
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String

Dim ColumnsSchema As ADODB.Recordset

Dim rsT As Variant

Dim i As Integer

For i = 0 To 2

rsT = Join(Application.Transpose(ThisWorkbook.Sheets("Prices").Range(Cells(3 + i * 10000, 9), Cells(10002 + i * 10000, 9)).Value), " ")


' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=DB1;" 'rest of the string blackened


' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset

'Open the connection and execute.
conn.Open sConnString

Set rs = conn.Execute(rsT)


Next i

' Clean up


If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing


End Sub

我当前的问题是,一旦我将计数器 i 增加到 3,因此使用 for 循环插入超过 30000,它会导致溢出错误。我已经尝试将其拆分为较小的块,并且计数器会变为 49:类似错误。

工作表“价格”中引用的单元格似乎都正确。这就是为什么我只在这里发布 VBA 代码。由于我对 VBA 和所用对象的限制不是很熟悉,所以我预计会出现问题,也许这里有更多 VBA 经验的人可以一目了然。

我们非常感谢您的任何建议,非常感谢您抽出宝贵时间阅读这篇文章。希望我至少可以让我的情况足够清楚。

【问题讨论】:

  • Dim i As Long
  • 另外,如果 10002 + i * 10000 超过 1,048,576 则会出错,因为 Excel 没有那么多行。
  • 为什么值为 3 的整数会导致溢出的答案是here。因为计算 10002 + i * 10000 中的文字数字

标签: sql excel vba adodb


【解决方案1】:

您可以运行多个查询,而无需每次都创建新连接。

Option Explicit

Sub insert()

    Const BATCH_SIZE = 10000 ' 10,000
    
    'Declare Variables
    Dim conn As ADODB.Connection, sConnString As String, SQL As String
    Dim ws As Worksheet, r As Long, LastRow As Long, n As Long
    Dim t0 As Single: t0 = Timer
       
    ' Create the connection string.
    sConnString = "Provider=SQLOLEDB;Data Source=DB1;" 'rest of the string blackened
    
    ' Create the Connection
    Set conn = New ADODB.Connection
    conn.Open sConnString
    
    Set ws = ThisWorkbook.Sheets("Prices")
    With ws
         LastRow = .Cells(Rows.Count, 9).End(xlUp).Row ' col I
         For r = 3 To LastRow Step BATCH_SIZE
             SQL = Join(Application.Transpose(ws.Cells(r, 9).Resize(BATCH_SIZE).Value), " ")
             conn.Execute SQL
             n = n + 1
         Next
    End With
      
    ' Clean up
    If CBool(conn.State And adStateOpen) Then conn.Close
    Set conn = Nothing
    Set rs = Nothing

    MsgBox LastRow - 2 & " rows in " & n & " batches of max size " & BATCH_SIZE, _
           vbInformation, Format(t0 - Timer, "0.0 secs")
    
End Sub

【讨论】:

  • 非常感谢。只要声明我的柜台就可以立即解决我的问题。我非常怀疑 Join 或 Transpose 可能有未知的限制,以至于这完全击中了我这边的盲点。还要感谢 CDP1802。那是我可能要做的下一步。我有点担心我们的网络和安全设置可能会导致随机断开连接,所以我决定一开始就安全地玩,因为速度也不是那么大的限制。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多