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
}
Connections are automatically pooled, and calling Dispose / Close on the connection does not physically close the connection (under normal circumstances).
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.
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.
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.
No, SqlCommand never attempts to close/dispose of the connection.
No, the connection object will not be disposed until you dispose it explicitly. But my recommendation is to use using blocks whenever you can.
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