Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does End Using close an open SQL Connection

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  
like image 902
rjrapson Avatar asked Dec 17 '08 21:12

rjrapson


People also ask

Does using close a SQL connection?

Answers. Yes. When the using block ends, the connection automatically closes (That is what IDisposable is for). So, do not close the connection explicitly.

When should I close SQL connection?

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.

How do I close a SQL connection?

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 .)

Should you keep SQL connection open?

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!


2 Answers

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.

like image 166
matt b Avatar answered Oct 12 '22 22:10

matt b


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.

like image 30
Darin Dimitrov Avatar answered Oct 12 '22 22:10

Darin Dimitrov