Joe Cambareri
Joe Cambareri

Reputation: 115

Closing an OleDbConnection

Just a general question, if I open an OleDbConnection in my program, should I close it at some point? I only ask because I've seen a few tutorials where the presenter doesn't include a statement to close the connection.

In my specific circumstances, I open a connection to access an Excel file, fill a DataTable and grab some values. After that though, there is no reason for me to have the connection open and I'm thinking it would probably cause some issues if I left it open.

Also, is the statement conn.Close(); sufficient to close the connection?

Upvotes: 2

Views: 4989

Answers (2)

Izzy
Izzy

Reputation: 6876

You should make use of the using block which will ensure the connection is closed and disposed correctly.

using (OleDbConnection connection = new OleDbConnection(connectionString))
{
  connection.Open();
  //Do some work
}//The connection is automatically closed when the code exits the using block.

Further reading here

Upvotes: 5

Patrick Hofman
Patrick Hofman

Reputation: 157136

Yes, you should close your connection as soon as you are done with it. If you use your connection in one method and not immediately after it again, close and dispose it, so it can be cleaned up.

You should wrap the creation of a connection in a using statement since that will even close and dispose the connection when an exception occurs.

using (OleDbConnection conn = new OleDbConnection(...))
{
    // use the connection inside here
}

Upvotes: 7

Related Questions