VBA ODBC 更新
这是我用来更新 SQL 数据库的代码:
Public Sub main()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Set cnn = New ADODB.Connection
Set rst = New ADODB.Recordset
cnn.Open "ConnectionName"
rst.ActiveConnection = cnn
rst.CursorLocation = adUseServer
rst.Source = "Update Table ..."
rst.Open
Set rst = Nothing
Set cnn = Nothing
End Sub
我想知道的是打开第一个对象后是否以及如何处理它。我要关闭它吗?当我尝试执行 rst.Close 时,出现错误:“对象关闭时不允许操作”。该代码在没有 rst.Close 的情况下工作正常,我想知道不关闭该对象是否有任何危险。
This is the code I'm using to update an SQL database:
Public Sub main()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Set cnn = New ADODB.Connection
Set rst = New ADODB.Recordset
cnn.Open "ConnectionName"
rst.ActiveConnection = cnn
rst.CursorLocation = adUseServer
rst.Source = "Update Table ..."
rst.Open
Set rst = Nothing
Set cnn = Nothing
End Sub
What I want to know is if and how I should deal with the rst object after opening it. Do I close it? When I try doing rst.Close, I get the error: "Operation is not allowed when the object is closed". The code works fine without rst.Close, I'm wondering if there are any dangers to not closing the object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新不返回任何行,因此无需打开记录集。
您可以直接使用以下命令执行语句:
Connection.Execute "Update Table ...", [flags]
要回答您的问题,在
.Open
之后,记录集被关闭(其.state
将是adStateClosed
),因为没有返回任何数据,因此将其设置为空就足够了。An update returns no rows, so no need to open a recordset.
You can execute the statement directly using:
Connection.Execute "Update Table ...", [flags]
To answer your question, after
.Open
the recordset is closed (its.state
will beadStateClosed
) as no data has been returned, so setting it to nothing is sufficent.UPDATE
操作不返回结果集。因此,如果使用Recordset
对象执行,则会产生一个空且关闭的记录集。无论如何它都无法关闭,因为它从未被打开过。经验法则是:
但是,因为您执行的命令无论如何都不会返回数据,所以首选方法是:
或者,如果您的 SQL 是没有参数的固定字符串,
另外,请更改
rst.ActiveConnection = cnn
到设置 rst.ActiveConnection = cnn
。An
UPDATE
operation does not return a resultset. Therefore, if executed with aRecordset
object, it results in an empty and closed recordset. It cannot be closed anyway because it has never been opened.A rule of thumb is:
But, because you are executing a command that's not going to return data anyway, the preferred way is:
Or, if your SQL is a fixed string that doesn't have parameters,
Also, please change
rst.ActiveConnection = cnn
toSet rst.ActiveConnection = cnn
.