2009-09-12 168 views
4

我有使用MySql数据库的ac#应用程序,问题是经过一段时间的不活动(8小时)或连接到数据库是主机的服务器丢失后,连接到数据库关闭,数据库查询无法执行。我如何启用自动重新连接到数据库。连接丢失后自动重新连接到MySql

此致敬礼。

+1

请详细说明一下 – roosteronacid 2009-09-12 15:17:32

回答

0

如果尝试访问数据库失败,请再次运行连接命令。

1

在您的应用程序中,在进行任何查询之前,请测试您的连接是否仍处于活动状态。如果不是,则重新连接。 Et瞧!

2

我认为首先应该解决的是,为什么连接要连续8小时开放?

我认为,在大多数情况下,你会连接到数据库,做你的事,并关闭它:

using (var conn = new MySqlConnection(connString)) 
{ 
    // do what you need here 
} 

using块将创建只是块内有效的连接。块结束时,将在连接上调用Dispose方法,并关闭并正确处理连接对象。这将阻止您的应用程序在不需要时使用可用连接。

如果你在一个情况下,你需要确定,如果连接是打开的,您的连接变量将有一个State财产,这将是一个ConnectionState枚举。

可以使用这样的检查:

if (conn.State != ConnectionState.Open) 
{ 
    conn = new MySqlConnection(connString); 
} 

希望有所帮助。

0

您可以在连接字符串中使用选项keepalivekeepalivetimeout。对此,最好使用MySqlConnectionStringBuilder

0

谢谢您的回答和建议。我有这个要求,因为持久性委托给非托管代码,在我的C#代码中,我只调用这个API。

我解决了我的问题,通过将具有28800秒(8小时)的wait_timeout MySQL参数作为非活动时间段的默认值。

0

while (conn.State != ConnectionState.Open) { sleep(1); // sleep 1 second, depends what function u use here if using timer namespace mightt need differnt function. this type of code is good for cloud type dbs like godaddy/1&1/amazon cloud. where connection can be asummed unreliable due too heavy cloud lag. conn = new MySqlConnection(connString); }

替代可以是:

int counter = 0; 
int NUM_RETRIES = 10; 

while (conn.State != ConnectionState.Open && counter < NUM_RETRIES) 
{ 
System.Threading.Thread.Sleep(1000);//sleep(1); // sleep 1 second (if webservice better to sleep for 50-100 ms), depends what function u use here if using timer namespace mightt need differnt function. this type of code is good for cloud type dbs like godaddy/1&1/amazon cloud. where connection can be asummed unreliable due too heavy cloud lag. 
    conn = new MySqlConnection(connString); 
counter++; 
} 

还此。 https://dev.mysql.com/doc/refman/5.7/en/auto-reconnect.html