Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does .net SqlCommand.ExecuteReader close connection?

In this sentence:

myCommand.ExecuteReader(CommandBehavior.CloseConnection)

does it close connection in case of exception?

like image 434
Antonio Avatar asked Dec 31 '22 09:12

Antonio


1 Answers

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.

like image 56
Stefan Schultze Avatar answered Jan 14 '23 19:01

Stefan Schultze