Search code examples
c#mysqlconnectionconnector

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 ?


Solution

  • 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.