简体   繁体   中英

MySQL Connector connection reuse

I have a class with a MySqlConnection object that I reuse across my application

public class MySqlWrapper : IDbConnection
{
    MySqlConnection _connection = new MySqlConnection();
}

I have a few methods using this

public void UseDB()
{
    _connection.Open();  
    // Do highly important stuff  
    _connection.Close();
}

It does happen that Open() call fails because the connection is already opened.
Yes, all of my Open() have a matching Close()

Now a solution I've found would be to clone the connection everytime i use it

    MySqlConnection connClone = _connection.Clone();
    connClone.Open();

For some reason this snippet smells bad code. Is it safe to use? Is there another way I do not know off to handle open/close ?

Perhaps consider refactoring that class a bit, and instantiate your MySqlConnection on each use in each method?

Also consider C#'s using statement:

using (var myConn = new MySqlConnection())
{      
    myConn.Open();
    //do some work.
}
//the MySqlConnection is now out of scope.

If that's not a viable option / refactoring, then consider wrapping both the .Open() and .Close() in a try catch block of their own.

You can check if a connection is already opened with _connection.ConnectionState == ConnectionState.Open .

I would recommend making your class implement IDisposable and dispose the MySqlConnection in the dispose method and initialize the connection inside the constructor (or a initialize method). You can then use ConnectionState to determine if you need to re-initialize your connection before you run a query.

You should not connect/disconnect between each query, that would be terribly slow.

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