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 ev
I know the question is related to closing the connection which will be the case; however, the connection won't be disposed. To dispose the connection itself, you need to enclose it a using block as well:
using (DBConnection conn = new ...)
{
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; }
}
}
}
UPDATE I thought this was an interesting question so I wrote the following test:
string connString = @"Data Source=.\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True;";
SqlConnection conn = new SqlConnection(connString);
try
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select from MSdbms";
conn.Open();
Console.WriteLine(conn.State);
using (IDataReader reader = cmd.ExecuteReader())//Will throw an exception - Invalid SQL syntax -see setting CommandText above
{
Console.WriteLine("here");
}
}
}
catch(Exception ex)
{ Console.WriteLine(conn.State); } //prints Open
If the line using (IDataReader reader = cmd.ExecuteReader()) is changed to: using (DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) then it prints Closed. Something to keep in mind.