vba - 将记录集插入 SQL Server 表 (VB ADODB)
问题描述
我在 Excel 上有一个表格,范围为 A1:Sn(其中 n 是 LastRow)。以前我习惯在每一行中循环并一一插入。
这工作正常,我可以求助于它,但我希望将整个记录集("A1:S" & LastRow)
插入 SQL 表,而不是逐行循环。
这样做的原因是,如果我作为一个完整的记录集插入将被视为 1x 操作,因此将为多个用户生成收据 ID 会变得更加容易。
代码
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
dim i as long
dim LastRow as long
LastRow = Sheets("Project_Name").Cells(Rows.count, "B").End(xlUp).row
con.Open "Provider=SQLOLEDB; Data Source=LO1WPFSASDB001 ; Initial Catalog=database; User ID=username; Password=password; Trusted_Connection=no"
rs.Open "SELECT * from table;", con, adOpenKeyset, adLockOptimistic
With rs
for i = 1 to LastRow
.addnew
!somevalue = range("A1:S" & LastRow)
.update
next
.Close
End With
con.Close
Set con = Nothing
Set rs = Nothing
我似乎无法让它工作。我会很感激你的意见。
解决方案
看来您需要更改循环结构。
Dim con As ADODB.Connection
Dim Rs As ADODB.Recordset
Dim strConn As String
Dim i As Long, j As Integer
Dim LastRow As Long
Dim vDB
Set con = New ADODB.Connection
Set Rs = New ADODB.Recordset
LastRow = Sheets("Project_Name").Cells(Rows.Count, "B").End(xlUp).Row
vDB = Sheets("Project_Name").Range("A1:S" & LastRow)
strConn = "Provider=SQLOLEDB; Data Source=LO1WPFSASDB001 ; Initial Catalog=database; User ID=username; Password=password; Trusted_Connection=no"
With Rs
.ActiveConnection = strConn
.CursorType = adOpenDynamic
.LockType = adLockOptimistic
.Open
For i = 1 To UBound(vDB, 1)
.AddNew
For j = 1 To UBound(vDB, 2)
.Fields(j) = vDB(i, j)
Next j
.Update
Next i
End With
With Rs
End With
Set Rs = Nothing
推荐阅读
- javascript - 使用 react JS 打印收据
- postgresql - 如何在预定时间获得 postgresql 与 pgcenter 的活动连接?
- javascript - 带有 jquery 或 ajax 的烧瓶返回 {"readyState":0,"status":0,"statusText":"error"}
- c# - 在 c# 中识别 iPad ios13 和 MAC OS 之间的设备
- python-3.x - 将屏蔽值分配给熊猫中的不同行
- javascript - 我无法在 id="Main" 上写字或做出反应
- python - 在真实路径中获取异常
- react-native - Googleapis Androidpublisher:如何弄清楚函数的新路径是什么?
- c# - 如何水晶报表传递参数
- pandas - 尝试通过正则表达式预处理文本文件,因为它上面的数字条目很少