Does instantiating a new SqlConnection in the SqlCommand's constructor close it?
For example:
using (SqlCommand comm = new SqlCommand(query, new SqlConnection(connString))
{
// do some stuff
}
Will that call .Close() on the connection?
Does instantiating a new SqlConnection in the SqlCommand's constructor close it?
For example:
using (SqlCommand comm = new SqlCommand(query, new SqlConnection(connString))
{
// do some stuff
}
Will that call .Close() on the connection?
No, it won't. SqlCommand doesn't own the connection, so it's not going to Close or Dispose of its own accord.
You'll need to either call Close yourself or, probably better, wrap it in a using statement so that Dispose is called when you're finished with it:
using (var connection = new SqlConnection(connString))
using (var command = new SqlCommand(query, connection))
{
// do some stuff
}
No, Disposing of the Command will not close the Connection. A better approach would be to also wrap the SqlCommand in a using block as well
using (SqlConnection conn = new SqlConnection(connstring)) { conn.Open(); using (SqlCommand cmd = new SqlCommand(cmdstring, conn)) { cmd.ExecuteNonQuery(); } }