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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With