简体   繁体   English

连接状态MySql Connector / NET

[英]Connection state MySql Connector/NET

I'm using the latest stable MySql Connector/NET 6.5.4.0. 我正在使用最新的稳定的MySql Connector / NET 6.5.4.0。

I open a connection to a MySQL database. 我打开与MySQL数据库的连接。 In the C# code, the Connection.State property is Open . 在C#代码中, Connection.State属性为Open I do some magic stuf, and while I'm doing that, I kill the connection server side. 我做了一些魔术操作,而在执行操作时,我杀死了连接服务器端。 However, in the code the State is still Open . 但是,在代码中State仍为Open

I ran into this problem because I save instances of my database class in a static variable per session (Dictionary). 我遇到了这个问题,因为我在每个会话中将数据库类的实例保存在静态变量中(字典)。 If a user does a request, the database class is pulled from this variable, and queries are fired to it. 如果用户发出请求,则从该变量中提取数据库类,并向其触发查询。 However, if the connection closes server side (killed by de sysadmin, wait timeout elapsed), the state isn't updated. 但是,如果连接关闭服务器端(被sysadmin杀死,等待超时已过去),则状态不会更新。

Is there a workaround for this problem? 有解决此问题的方法吗? My colleague allready submitted a bug report for it (http://bugs.mysql.com/bug.php?id=64991). 我的同事已经准备好为其提交错误报告(http://bugs.mysql.com/bug.php?id=64991)。

Close and Open before execution, is very bad for the performance, so no option. 执行前先关闭再打开,对性能非常不利,因此没有选择。

Putting aside design issues (should really be pooling), based on your comment: 根据您的评论,搁置设计问题(实际上应该是汇总):

Connection pooling is turned off in this case, I'll look into the Ping method. 在这种情况下,连接池已关闭,我将研究Ping方法。 If this connection is closed, I get an 'Fatal error encountered during command execution' 如果关闭此连接,则会收到“命令执行期间遇到致命错误”

Is there any reason you're not recreating the connection if the ping fails? 如果ping失败,您是否有任何理由不重新建立连接?

private static MySqlConnection conn;
private static int maxRetries;

private static void connect()
{
    conn = <connect code>;
}

private static MySqlConection GetConnectionRetry(int count)
{
    if (conn != null && conn.State == Open)
    {
        try
        {
            conn.Ping();
            return conn;
        }
        catch (Exception e) // better be specific here
        {
            if (count <= maxRetries)
            {
                connect();
                return GetConnectionRetry(count + 1);
            }
            else throw e;
        }
    }
    else
    {
        connect();
        return GetConnectionRetry(count + 1);
    }
}

static MySqlConnection GetConnection()
{
    return GetConnectionRetry(1);
}

I would advise you to use the singelton-pattern for the connection. 我建议您使用singelton模式进行连接。 So you can ensure that there is always just one connection open and you only have to manage this one. 因此,您可以确保始终只有一个连接处于打开状态,而您只需要管理该连接即可。

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

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