If I wrap a SQLConnection in a Using, should I close it or does the end using handle it?
using cn as new system.data.sqlclient.sqlconnection() cn.open '{do a bunch of other stuff with commands and datareaders here} cn.close 'Do I need this? end using
Answers. Yes. When the using block ends, the connection automatically closes (That is what IDisposable is for). So, do not close the connection explicitly.
You are doing the best practices. Only open it right before you are going to query it, and close it as soon as you can. This kind of thing may seem wasteful at first, but it actually makes your application more scalable in the long run.
Select the connection profile of the connection you want to close, located under the Active Connections node. Click Close Connection . (Alternatively, click Close All Connections .)
From MSDN, "Note If the SqlConnection goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling Close or Dispose." Cheers!
Exiting a using block calls .Dispose() on the object in question (cn
in your example) which for a SqlConnection will close the connection and any open resources.
More precisely calling Dispose or Close will mark the underlying physical connection as "Not in use" - but doesn't really close it. A "Not in use" connection that isn't yet physically closed is thus available for pooling. Therefore - calling Dispose would return a connection to the connection pool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With