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; }
}
}
}
Yes even if it throws an exception it will close the connection.
If you do not specify
CommandBehavior.CloseConnectionand you close the connection, your calling code cannot access the contents of the reader.Also from MSDN:
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/finallyin this case the reader will be closed which then will close the database connection.