0

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?

user3093863
  • 21
  • 1
  • 4

2 Answers2

1

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
}
Charles Mager
  • 25,735
  • 2
  • 35
  • 45
0

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();
    }
}

https://stackoverflow.com/a/60934/64976

Community
  • 1
  • 1