Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a using block close a database connection?

Tags:

c#

database

using

using (DbConnection conn = new DbConnection()) {     // do stuff with database } 

Will the using block call conn.Close()?

like image 702
Craig Johnston Avatar asked Mar 09 '11 09:03

Craig Johnston


People also ask

Will using statement close 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.

Do SQL connections close automatically?

If the application ends, the connection gets closed, along with everything else that was opened.

When should you close a database connection?

For the purpose of safe coding, you should always close database connections explicitly to make sure that the code was able to close itself gracefully and to prevent any other objects from reusing the same connection after you are done with it.


1 Answers

Yes, it will; the implementation of DbConnection.Dispose() calls Close() (and so do its derived implementations).

like image 186
BoltClock Avatar answered Sep 21 '22 02:09

BoltClock