英文:
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
' SET ALL VARIABLES
Database_Name = "<DATABASE_NAME>" ' Enter your database name here
Table_Name = "<TABLE_NAME>"
WkbName = ThisWorkbook.Name
SheetName = "mine_ufl_input" ' WHERE RS IS
' SET SQL STRING
' PREPARED STATEMENT
strSQL = "INSERT INTO [ufl]." & Table_Name & _
" ([Country], [Asset_type], [Year], [Quarter],[updated_budget_abs])" & _
" VALUES (?, ?, ?, ?, ?)"
' SET TO CONNECTION VARIABLES
Set DBCONT = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
DBCONT.ConnectionString = "Provider=sqloledb;Server=<SERVER_NAME>;Database=<DATABASE_NAME>;Trusted_connection=yes;"
DBCONT.Open
DBCONT.Execute "truncate table <TABLE_NAME>"
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 ' CONNECTION OBJECT
.CommandText = strSQL ' SQL STRING
.CommandType = adCmdText
' BINDING PARAMETERS
.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))
'... rest of parameters
.Execute ' RUN ACTION
End With
Set cmd = Nothing
Next i
Call CloseDB
MsgBox i & " Lines Imported."
End Sub
答案1
得分: 1
以下是代码部分的翻译:
Takes <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
' SET ALL VARIABLES
dbName = "<DATABASE_NAME>" ' Enter your database name here
tableName = "<TABLENAME>"
' SET SQL STRING
SQL = "INSERT INTO [ufl]." & tableName & _
" (Country, Asset_type, Year, Quarter,updated_budget_abs)" & _
" VALUES (?, ?, ?, ?, ?)"
' SET TO CONNECTION VARIABLES
sConn = "Provider=sqloledb;Server=<SERVER_NAME>;" & _
"Database=" & dbName & ";Trusted_connection=yes;"
Set dbConn = New ADODB.Connection
With dbConn
.ConnectionString = sConn
.Open
.Execute "TRUNCATE TABLE " & tableName
End With
' PREPARED STATEMENT
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = dbConn
.CommandText = SQL
.CommandType = adCmdText
.Prepared = True
' BINDING PARAMETERS
For p = 0 To 4
.Parameters.Append .CreateParameter("P" & p, adVarChar, adParamInput, 255)
Next
End With
Dim arFields: arFields = Array(1, 2, 3, 4, 17) ' columns
t0 = Timer
' INSERT RECORDS
Set ws = ActiveSheet ' or Thisworkbook.sheets(""mine_ufl_input")
With ws
lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
dbConn.Execute "BEGIN TRANSACTION"
For r = 2 To lastrow
For p = 0 To 4
cmd.Parameters(p).Value = .Cells(r, arFields(p))
Next
cmd.Execute ' RUN ACTION
Next
dbConn.Execute "COMMIT TRANSACTION"
End With
'Call CloseDB
MsgBox lastrow - 1 & " Lines Imported.", _
vbInformation, Format(Timer - t0, "0.0 secs")
End Sub
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论