Is it necessary to close an Adodb.recordset object before setting it to nothing?

人走茶凉 提交于 2019-12-21 03:58:18

问题


Dim rs as ADODB.Recordset
set rs = ReturnARecordset 'assume ReturnARecordset does just that...

'do something with rs

rs.Close
set rs = Nothing

Is it necessary to call rs.Close before setting it to nothing?

Edit: We have one global connection that we keep open for the duration of the application and all recordset objects use this same connection. I see two answers below talking about the need to close recordsets in order to ensure connections aren't left hanging open. To me that sounds like a lot of silly talk because connections are controlled with connection objects, not recordset objects right? But please let me know if I'm missing something here...


回答1:


The only reason calling Close explicitly is when you are not sure if the recordset is referenced from somewhere else in your project, usually a result of some sloppy coding.

Dim rs as ADODB.Recordset
Set rs = ReturnARecordset
...
MyControl.ObscureMethod rs
...
Set rs = Nothing

Last line is supposed to terminate the recordset instance without calling Close explicitly, unless MyControl is holding an extra reference and thus preventing normal tear-down. Calling Close on rs will make sure MyControl cannot use its reference for anything useful, crashing in flames in the meantime.




回答2:


Yes, this does more than just force a garbage collection it also tells the server the connection is being terminated, this avoids having multiple open orphaned connections (they will eventually time-out by themselves) but its always best practise to close them out.

This is especially apparent when ADODB is using a remote connection rather than a local one.




回答3:


You can run into ODBC or OLEDB Pooling issues, which keep a connection open and tie up a pool slot:

Common causes of connection creep include:

The ADO Connection and Recordset objects are not actually closed. If you don't explicitly close them, they won't be released into the pool. This is probably the single most frequent cause of connection creep.

An ADO object you created (especially a Connection object) was not explicitly released. Explicitly releasing objects you create is just good programming practice. If you allocate memory, release it. Depending on the language you are using, letting a variable go out of scope may or may not result in it being released.

See Pooling in the Microsoft Data Access Components

And if there is any chance of .Net Interop involved be wary: there are lots of warnings about problems caused due to the lazy way COM object (or contained object) release occurs under .Net's garbage collection.



来源:https://stackoverflow.com/questions/8380185/is-it-necessary-to-close-an-adodb-recordset-object-before-setting-it-to-nothing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!