Pergunta

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 ?

Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top