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

后端 未结 4 1454
猫巷女王i
猫巷女王i 2021-02-13 19:05
Dim rs as ADODB.Recordset
set rs = ReturnARecordset \'assume ReturnARecordset does just that...

\'do something with rs

rs.Close
set rs = Nothing

Is i

相关标签:
4条回答
  • 2021-02-13 19:52

    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.

    0 讨论(0)
  • I needed to write many files. If I didn't close the connection after each file written then I got extraneous garbage at the end of subsequent files.

    fsT.Close
    

    followed by

    fsT.Open
    

    to "refresh" the output stream. So when I saved a new file, it was "clean".

    0 讨论(0)
  • 2021-02-13 20:05

    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.

    0 讨论(0)
  • 2021-02-13 20:08

    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.

    0 讨论(0)
提交回复
热议问题