Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does connection close when command is disposed and the connection is defined directly on the command?

I know that a lot of examples exist where a SqlConnection is defined and then a SqlCommand is defined, both in Using blocks:

using (var conn = new SqlConnection(connString)) {
      using (var cmd = new SqlCommand()) {
        cmd.Connection = conn;
        //open the connection
      }
}

My question: If I define the connection directly on the SqlCommand, does the connection close when the command is disposed?

using (var cmd = new SqlCommand()) {
      cmd.Connection = new SqlConnection(connString);
      //open the connection
}
like image 361
Dela Avatar asked Jan 04 '09 01:01

Dela


People also ask

Does dispose close connection?

Connections are automatically pooled, and calling Dispose / Close on the connection does not physically close the connection (under normal circumstances).

Does disposing a SQL connection close it?

When you call "Dispose()" on a SqlConnection, internally, it calls "Close()", too. There is no worry - you are free to use Close() manually, or just let Dispose() do it for you.

What is the difference between close and dispose?

Close() will simply close the connection to the server as defined in the connection string. The Connection can be used/re-opened after this point. Connection. Dispose() will clean up completely, removing all unmanaged resources preventing that Connection from being used again.

Do I need to close SQL connection?

No, it is not necessary to Close a connection before calling Dispose. Show activity on this post. No, the SqlConnection class inherits from IDisposable, and when the end of using (for the connection object) is encountered, it automatically calls the Dispose on the SqlConnection class.


2 Answers

No, SqlCommand never attempts to close/dispose of the connection.

like image 188
Robert C. Barth Avatar answered Sep 28 '22 16:09

Robert C. Barth


No, the connection object will not be disposed until you dispose it explicitly. But my recommendation is to use using blocks whenever you can.

like image 44
milot Avatar answered Sep 28 '22 18:09

milot