【问题标题】:Insert recordset into SQL Server Table (VB ADODB)将记录集插入 SQL Server 表 (VB ADODB)
【发布时间】:2018-07-12 15:17:22
【问题描述】:

我在 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

我似乎无法让它工作。我会很感激你的意见。

【问题讨论】:

  • 循环后调用更新?
  • 对不起.. 请详细说明?
  • 我认为您可以添加到记录集,然后在您进行更新后进行更新。
  • 考虑使用 MS Access 将数据存储在表中,以便对 SQL Server 进行批量追加查询。

标签: vba excel


【解决方案1】:

看来你需要改变循环结构。

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

【讨论】:

    【解决方案2】:

    您仍然需要在excel上循环数据并插入/添加它。

    遵循您当前的代码。第二个循环是插入列。

    for i = 1 to LastRow
        .addnew
        For n = 0 To .Fields.Count - 1
            .Fields(n).Value = Cells(i, n + 1)
        Next n
        .update
    next
    

    我会采取不同的方法来避免第二个循环。而不是使用 .addnew 我会在 excel 中循环数据,创建 INSERT 字符串并执行 .Execute "INSERT ..." 代替。使用这个方法可以跳过rs.Open,只要打开连接执行就可以了。

    for i = 1 to LastRow
        sqlString = "INSERT INTO TableName (Field1, Field2, Field3, Field4...) VALUES (Cells(i, 1), Cells(i, 2), Cells(i, 3), Cells(i, 4)...)"
        con.Execute(sqlString)
    next
    

    编辑:使用插入方法,必须用'标记将文本值括起来,否则INSERT语句将返回无效的值类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 2011-05-09
      • 2016-06-02
      • 2021-09-03
      • 1970-01-01
      相关资源
      最近更新 更多