简体   繁体   English

长时间连接后,MYSQL connector.net连接丢失

[英]MYSQL connector.net connection lost after long time

I have mysql connection to remote server with connector.net 6.7.4 我通过连接器6.net将mysql连接到远程服务器

like this: 像这样:

public MySqlConnection conn;
public MySqlCommand com;

public onStart()
{
   conn = new MySqlConnection("Server=xx.xx.xx.xx;Port=3306;Database=kbindb;Uid=collector; Pwd=xxx;");
   conn.Open();
   com = new MySqlCommand("SELECT * FROM blabla;", conn);
   timer.Interval=1000;
   timer.Enabled=True;

}   

public onTimerTick(bla bla)
{
    // timer.Enabled=False;
     MySqlDataReader dr = com.ExecuteReader();
     while(dr.Read()){
            //blabla
      }
     dr.Close();
     //timer.Enabled=True;
 }

Code is running succesfully but after 1-2 hours lock timer on this line : com.ExecuteReader(); 代码成功运行,但是在此行上经过1-2小时的锁定计时器后:com.ExecuteReader(); It can not handling with try catch. 它不能使用try catch处理。

What can I do? 我能做什么?

I wouldn't keep a connection to the database open any longer than you need it.. certainly not for hours. 我不会保持与数据库的连接打开的时间超过了您的需要。 I assume you're getting a timeout of some sort. 我认为您会遇到某种超时情况。

Try creating the connection inside the tick event, get your data, and dispose of the connection. 尝试在tick事件中创建连接,获取数据并处理该连接。 (The using statements in the following code will take care of disposing your resources.) (以下代码中的using语句将处理您的资源。)

public onStart()
{
   timer.Interval = 1000;

   timer.Enabled = true;
}   

public onTimerTick(...)
{
    timer.Enabled = false;

    using (var conn = new MySqlConnection("Server=xx.xx.xx.xx;Port=3306;Database=kbindb;Uid=collector; Pwd=xxx;"))
    {
        conn.Open();
        using (var com = new MySqlCommand("SELECT * FROM blabla;", conn))
        {
            var reader = com.ExecuteReader();

            while (dr.Read())
            {
                //blabla
            }
        }
    }

    timer.Enabled = true;
}

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

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