将记录集插入到SQL Server表(VB ADODB)

时间:2018-07-12 15:17:23

标签: excel vba excel-vba

我在Excel上有一个表格,范围为A1:Sn(其中n是LastRow)。以前,我曾经循环遍历每一行,并将其一一插入。

这很好用,我可以重用它,但是我希望将整个记录集("A1:S" & LastRow)插入SQL Table中,而不是逐行循环。

之所以这样,是因为如果我将整个记录集插入将被视为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

我似乎无法使其正常工作。谢谢您的投入。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您仍然需要在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方法,必须用'标记括住文本值,否则INSERT语句将返回无效的值类型。