Which one of these samples it the correct way to close the connection using Command Behavior.
A.
SqlDataReader rdr = new SqlDataReader();
string sql = @”sql statement”;
SqlConnection conn = connection.GetConnection();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
Console.WriteLine(“{0}”, rdr);
B.
SqlDataReader rdr = new SqlDataReader();
string sql = @”sql statement”;
SqlConnection conn = connection.GetConnection();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.close();
Console.WriteLine(“{0}”, rdr);
C.
SqlDataReader rdr = new SqlDataReader();
string sql = @”sql statement”;
SqlConnection conn = connection.GetConnection();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
conn.close();
Console.WriteLine(“{0}”, rdr);
D.
using (SqlDataReader rdr = new SqlDataReader())
{
string sql = @”sql statement”;
SqlConnection conn = connection.GetConnection();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
Console.WriteLine(“{0}”, rdr);
}
Explanation:
An alternative to explicitly closing the Connection is to pass CommandBehavior.CloseConnection to
the ExecuteReader method to ensure that the associated connection is closed when the DataReader
is closed. This is especially useful if you are returning a DataReader from a method and do not have
control over the closing of the DataReader or associated connection. When you close the data
reader and you use CommandBehavior.CloseConnection – the SQLconnection also closes
http://msdn.microsoft.com/en-us/library/ms971481.aspx