Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will ExecuteReader(CommandBehavior.CloseConnection) always close connection?

Is it safe to write this helper method like this? Will it always close the connection? I understend if all goes well, it will, but will ExecuteReader close the connection even if it throws?

    public static IEnumerable<DbDataRecord> ExecuteSelect(string commandText, DbConnection conn)
    {
        using (DbCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = commandText;
            conn.Open();
            using (DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                foreach (DbDataRecord record in reader) { yield return record; }
            }
        }
    }
like image 596
Eugene Ryabtsev Avatar asked May 09 '12 15:05

Eugene Ryabtsev


2 Answers

Yes even if it throws an exception it will close the connection. If you do not specify CommandBehavior.CloseConnection and you close the connection, your calling code cannot access the contents of the reader.

Also from MSDN:

When the command is executed, the associated Connection object is closed when the associated DataReader object is closed.

You should ensure that the reader is closed when you are done with it. The nice thing about all of this is you've got it wrapped around a using statement and you aren't using try/catch/finally in this case the reader will be closed which then will close the database connection.

like image 180
JonH Avatar answered Sep 20 '22 16:09

JonH


Personally I prefer a using clause statement to close/dispose the connection , simply for parallel construction reasons - same as in good English Grammar.
From my point of view using the CommandBehavior is not balanced and therefore unpredictable.

I constantly tell to my developers to go simple and consistent.
As if they forget to set the CommandBehavior...

I won't see it...
but if they don't use a using statement...
I will see it as it is very important.

like image 21
Doug Avatar answered Sep 19 '22 16:09

Doug