Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Not Close a Database Connection in a Finally Block

Major Edit: I misread the article! The comment was in regards to the finalize method of the the class not the finally block :). Apologies.

I was just reading that you should not close or dispose a database connection within a finally block but the article did not explain why. I can not seem to find a clear explanation as to why you would not want to do this.

Here is the article

like image 869
William Edmondson Avatar asked Nov 28 '22 12:11

William Edmondson


2 Answers

If you look around, closing the connection in the finally block is one of the recommended ways of doing it. The article you were looking at probably recommended having a 'using' statement around the code that used the connection.

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = connection.CreateCommand();

    command.CommandText = "select * from someTable";

    // Execute the query here...put it in a datatable/dataset
}

The 'using' statement will ensure the Connection object gets disposed immediately after it's needed rather than waiting for the Garbage Collector to dispose of it.

like image 180
Justin Niessner Avatar answered Dec 10 '22 06:12

Justin Niessner


I have to disagree that you should not close or dispose of a database connection within a finally block.

Letting an unhandled (or even handled for that matter) exception leave open connections can take down a database pretty quickly if it has a lot of activity.

Closing a database connection is the defacto example of why to use the finally statement, IMHO. Of course, the using statement is my preferred method, which is maybe what the original author was going for.

Edit to the Major Edit: That makes sense now. You wouldn't want to leave closing your database connection up to the garbage collector.

like image 32
Aaron Daniels Avatar answered Dec 10 '22 05:12

Aaron Daniels