MySQL Connector 连接重用
我有一个带有 MySqlConnection 对象的类,我在应用程序中重用该对象。
public class MySqlWrapper : IDbConnection
{
MySqlConnection _connection = new MySqlConnection();
}
我有一些使用此方法的方法。
public void UseDB()
{
_connection.Open();
// Do highly important stuff
_connection.Close();
}
由于连接已打开,Open() 调用确实会失败。
是的,我所有的 Open() 都有一个匹配的 Close()
现在我发现的一个解决方案是每次使用它时克隆连接
MySqlConnection connClone = _connection.Clone();
connClone.Open();
由于某种原因,这个代码片段闻起来很糟糕。使用安全吗?还有另一种我不知道的方法来处理打开/关闭吗?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
_connection.ConnectionState == ConnectionState.Open
检查连接是否已打开。我建议您的类实现 IDisposable 并在 dispose 方法中处置 MySqlConnection 并在构造函数(或初始化方法)内初始化连接。然后,您可以使用 ConnectionState 来确定是否需要在运行查询之前重新初始化连接。
您不应该不在每个查询之间连接/断开连接,否则会非常慢。
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.
也许考虑稍微重构一下该类,并在每个方法中的每次使用时实例化您的 MySqlConnection ?
另请考虑 C# 的
using
语句:如果这不是可行的选项/重构,请考虑包装
.Open()
和.Close()
在自己的try catch
块中。Perhaps consider refactoring that class a bit, and instantiate your MySqlConnection on each use in each method?
Also consider C#'s
using
statement:If that's not a viable option / refactoring, then consider wrapping both the
.Open()
and.Close()
in atry catch
block of their own.