Sunday, February 22, 2009

Database Connection Open/Close

It seems trivial that you first open your connection, and eventually close it, but what happens when you're doing it in a loop, and one miss causes havoc forever until restart?

Make sure you open only if it's not closed, you close only if it's not open, and handle every exception. See following code example:

try //catch (Exception E)
{
try //finally close DB
{
// open only if not already open
if (oSqlConn.State!=ConnectionState.Open)
oSqlConn.Open();

// *** READ FROM DATABASE ***

}
finally
{
// close only if not already closed
if (oSqlConn.State != ConnectionState.Closed)
oSqlConn.Close();
}
}
catch (Exception E)
{
// handle exception
}

No comments:

Post a Comment