【MySQL】Error 2006:MYSQL server has gone away

本文介绍了一个MFC应用程序远程访问MYSQL数据库时遇到的连接超时问题及解决方法。通过调整数据库连接参数和启用自动重连功能,解决了长时间闲置后连接中断的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题的描述

MFC应用程序远程访问MYSQL数据库,程序初始化时创建一个连接池,通常保存10个连接用于访问数据库使用。该程序平时运行正常,但是程序正常使用后闲置一个晚上不关闭,第二天第一次使用报错如标题。

 

分析

使用命令查询数据库超时参数,服务器安装MYSQL 数据库版本为5.7.22。

查询命令:

show global variables like '%timeout';

查询结果如下: 

+-----------------------------+----------+
| Variable_name               | Value    |
+-----------------------------+----------+
| connect_timeout             | 10       |
| delayed_insert_timeout      | 300      |
| have_statement_timeout      | YES      |
| innodb_flush_log_at_timeout | 1        |
| innodb_lock_wait_timeout    | 50       |
| innodb_rollback_on_timeout  | OFF      |
| interactive_timeout         | 28800    |
| lock_wait_timeout           | 31536000 |
| net_read_timeout            | 30       |
| net_write_timeout           | 60       |
| rpl_stop_slave_timeout      | 31536000 |
| slave_net_timeout           | 60       |
| wait_timeout                | 28800    |
+-----------------------------+----------+
13 rows in set, 1 warning (0.00 sec)

参数wait_timeout值为28800,含义为28800秒,等于8小时。猜测MYSQL数据库在连接闲置超时后自动断开连接。

设置命令

set global wait_timeout=10;

将参数wait_timeout值设为10秒后,调试程序发现报错更为频繁,基本确认超时为该问题出现的原因。

 

解决方法

因为连接创建时,该连接的重连属性是关闭的。官方文档如下:

The MySQL client library can perform an automatic reconnection to the server if it finds that the connection is down when you attempt to send a statement to the server to be executed. If auto-reconnect is enabled, the library tries once to reconnect to the server and send the statement again.

Auto-reconnect is disabled by default.

因此必须在连接被创建时,设置该连接的重连属性,代码如下:

Connection::Connection(const string& host, unsigned port, const string& uname, const string& passwd, const string& db)
{
	char value = 1;

	m_conn = mysql_init(NULL);
	CONN_Throw(m_conn, mysql_real_connect(m_conn, host.c_str(),	uname.c_str(), passwd.c_str(), db.c_str(), port, NULL, 0));
	//this->charset("utf8");
	this->charset("gb2312");

	CONN_Throw(m_conn, mysql_options(m_conn, MYSQL_OPT_RECONNECT, (char *)&value));
}

网上也有许多其他解决该问题的方法,比如重设wait_timeout值为一个相对大的值、心跳包等等。本人觉得这些方法有点绕路,没有真正解决该问题。不妥之处,欢迎拍砖。

 

参考资料

MySQL server has gone away 问题的解决方法:https://www.cnblogs.com/fnlingnzb-learner/p/5984795.html

蛋疼的mysql_ping()以及MYSQL_OPT_RECONNECT:https://www.cnblogs.com/joeblackzqq/p/5614948.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值