Wednesday, October 04, 2006

[ADO.NET] 3 ways closing DataReader & Connection..

These are the 3 common ways I use to close the XDataReader and DB Connection...

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: