Excel VBA ADO - 写入访问数据库 - 只重复写入第一行记录集

时间:2014-11-07 15:00:55

标签: excel vba excel-vba ado

我有以下代码,它应该从oracle数据库获取记录集并将其写入访问数据库。它有大约2000行,我希望看到相同的转移访问。问题是,只有第一行数据以无限循环写入数据库! getconnection函数是一个只连接到Access的自定义函数。

我需要更改什么才能使代码生效?感谢

Sub InsertLine(rS As ADODB.recordset)

Dim adoConn As ADODB.Connection, adoComm As ADODB.Command

Set adoConn = GetConnection("access")
Set adoComm = New ADODB.Command

With adoComm

    Set .ActiveConnection = adoConn


        Do Until rS.EOF

            .CommandText = "INSERT INTO Products ([Product], [Category]) " & _
                            "VALUES(?,?)"

            .Parameters.Append .CreateParameter(Type:=adVarWChar, Value:=rS![ITMDSC], Size:=255)
            .Parameters.Append .CreateParameter(Type:=adVarWChar, Value:=rS![GRPDSC], Size:=255)

            .Execute

            rS.MoveNext

            Debug.Print rS![ITMDSC]
        Loop

End With

adoConn.Close

End Sub

感谢您的回复。我已经编辑了如下代码,但仍然遇到了同样的问题。或者我不明白你的意思?对不起,我很新。调试行显示正确的下一条记录。欢呼声

Sub InsertLine(rS As ADODB.recordset)

Dim adoConn As ADODB.Connection, adoComm As ADODB.Command, S As String, S2 As String

Set adoConn = GetConnection("access")
Set adoComm = New ADODB.Command

With adoComm

    Set .ActiveConnection = adoConn

        .CommandText = "INSERT INTO Products ([Product], [Category]) " & _
                            "VALUES(?,?)"

        .Parameters.Append .CreateParameter(Type:=adVarWChar, Value:=rS![ITMDSC], Size:=255)
        .Parameters.Append .CreateParameter(Type:=adVarWChar, Value:=rS![GRPDSC], Size:=255)

        S = rS![ITMDSC]
        S2 = rS![GRPDSC]

        Do Until rS.EOF
                .CommandText = "INSERT INTO Products ([Product], [Category]) " & _
                        "VALUES(S , S2)"

             .Execute
             rS.MoveNext

            Debug.Print rS![ITMDSC]
        Loop

End With

adoConn.Close

End Sub

1 个答案:

答案 0 :(得分:-1)

为什么要使用参数查询?它让它变得过于复杂......

.CommandText = "INSERT INTO Products ([Product], [Category]) " & _
               "VALUES('" & rS![ITMDSC] & "','" & rS![GRPDSC] & "')"
.Execute
 rS.MoveNext

如果你想使用参数查询,那么

.Parameters.Refresh

应清除当前参数