1. Use CommandBehavior.CloseConnection
SqlDataReader reader = null;
try
{
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
// do stuff
}
catch(Exception ex)
{
// logging error
}
finally
{
// conn will be closed when reader is closed
reader.Close();
}
2. Explicitly Close DataReader and Connection
SqlDataReader reader = null;
try
{
reader = cmd.ExecuteReader();
// do stuff
}
catch(Exception ex)
{
// logging error
}
finally
{
// conn will be closed when reader is closed
reader.Close();
conn.Close();
}
3. Use Using Statement
using(SqlConnection con = new SqlConnection(<connection string>))
{
using(SqlCommand cmd = new SqlCommand(<query>,conn))
{
using(SqlDataReader reader = cmd.ExecuteReader())
{
// do stuff
}
}
}
The first one is my preference, what about you?
No comments:
Post a Comment