Correct way to close database connection in event of exception.
Posted
by lowlyintern
on Stack Overflow
See other posts from Stack Overflow
or by lowlyintern
Published on 2010-04-21T07:41:18Z
Indexed on
2010/04/21
7:53 UTC
Read the original article
Hit count: 244
/I have some code of of the following form. Does this mean the connection is left open if there is an exception? Note, I am using a Microsoft SQL compact edition database./
try
{
SqlCeConnection conn = new SqlCeConnection(ConnectionString);
conn.Open();
using (SqlCeCommand cmd = new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
conn.Close();
}
catch (Exception ex)
{
ExceptionManager.HandleException(ex);
}
/*Surely a better way would be to declare a connection object before the try, establish
a connection inside the try block and close it in a finally block?
*/
SqlCeConnection conn = null;
try
{
conn = new SqlCeConnection(ConnectionString);
conn.Open();
using (SqlCeCommand cmd = new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
}
catch (Exception ex)
{
ExceptionManager.HandleException(ex);
}
finally
{
if( conn != null ) conn.Close();
}
© Stack Overflow or respective owner