MySQL Connector 连接重用

发布于 2024-10-17 04:58:20 字数 592 浏览 1 评论 0原文

我有一个带有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七度光 2024-10-24 04:58:20

您可以使用_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.

百合的盛世恋 2024-10-24 04:58:20

也许考虑稍微重构一下该类,并在每个方法中的每次使用时实例化您的 MySqlConnection ?

另请考虑 C# 的 using 语句:

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

如果这不是可行的选项/重构,请考虑包装 .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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文