Does .net SqlCommand.ExecuteReader close connection?

Antonio  picture Antonio · Oct 21, 2008 · Viewed 7.1k times · Source

In this sentence:

myCommand.ExecuteReader(CommandBehavior.CloseConnection)

does it close connection in case of exception?

Answer

Stefan Schultze picture Stefan Schultze · Oct 21, 2008

The safest way to do a "normal" query is

using (var conn = new SqlConnection("..."))
{
    conn.Open();
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "...";
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                // ...
            }
        }
    }
}

Exceptions can be caught outside this code.