简体   繁体   English

MySQL Connector连接重用

[英]MySQL Connector connection reuse

I have a class with a MySqlConnection object that I reuse across my application 我有一个带有MySqlConnection对象的类,可以在整个应用程序中重用

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. 确实发生了Open()调用失败的原因,因为该连接已经打开。
Yes, all of my Open() have a matching Close() 是的,我所有的Open()都有一个匹配的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? 也许考虑重构一下该类,并在每种方法的每次使用中实例化MySqlConnection?

Also consider C#'s using statement: 还要考虑C#的using语句:

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. 如果这不是可行的选择/重构,则考虑将.Open().Close()都包装在自己的try catch块中。

You can check if a connection is already opened with _connection.ConnectionState == ConnectionState.Open . 您可以使用_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). 我建议使您的类实现IDisposable并将MySqlConnection放置在dispose方法中,并在构造函数(或initialize方法)内部初始化连接。 You can then use ConnectionState to determine if you need to re-initialize your connection before you run a query. 然后,您可以使用ConnectionState确定在运行查询之前是否需要重新初始化连接。

You should not connect/disconnect between each query, that would be terribly slow. 应该每个查询,这将是非常缓慢之间的连接/断开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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