简体   繁体   中英

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?

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM