使用 VBA ADODB 连接更新 SQL 数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26611785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:02:24  来源:igfitidea点击:

Updating SQL Database Using VBA ADODB Connection

mysqlexcelvbaexcel-vba

提问by Jimjebus

I've been using ADODB for SQL queries to return data and copy it from a recordset to a workbook for a while and a new task is to update records but I have no clue on how to do update a record.

我一直在使用 ADODB 进行 SQL 查询来返回数据并将其从记录集复制到工作簿一段时间,一个新任务是更新记录,但我不知道如何更新记录。

This is an example of my code:

这是我的代码示例:

Dim con As ADODB.Connection
Dim rec As ADODB.Recordset

Set con = New ADODB.Connection
Set rec = New ADODB.Recordset

Dim sql As String

With con
    .Provider = "MSDASQL"
    .ConnectionString = "DSN=ukfast"
    .Open
End With

sql = "UPDATE crm_clients " & _
      "SET cheque_number = '" & chqNo & "' " & _
      "WHERE id = '' "

For Selecting data it was as easy as recordset.copyFromRecordset, but I have no clue about pushing an update back up to the database. I tried the .updatemethod but that only works for the record set itself not the database. I've also looked for some sort of execute method but come up short.

对于选择数据,它就像 一样简单recordset.copyFromRecordset,但我不知道将更新推回数据库。我尝试了该.update方法,但这只适用于记录集本身而不适用于数据库。我还寻找了某种执行方法,但没有找到。

What is the correct approach for updating a record using VBA?

使用 VBA 更新记录的正确方法是什么?

回答by cboden

You can use the Executemethod of the connection object for that:

您可以使用连接对象的Execute方法:

con.Execute(sql)