MySQL server has gone away的解决方法

用Python写了一个http服务,需要从mysql读数据库,第一天还好好的,第二天突然不行了。报错如下:

pymysql.err.OperationalError: (2006, 'MySQL server has gone away (0 bytes read on a total of 4 expected bytes)')

查了资料才知道,因为你的程序长时间没有去数据库取东西,mysql自动把你的连接断开了,默认是8个小时。

相关参数可以这样查看:

mysql>  show global variables like '%timeout%';

结果如下:

+----------------------------+-------+
| Variable_name              | Value |
+----------------------------+-------+
| connect_timeout            | 10    |
| delayed_insert_timeout     | 300   |
| innodb_lock_wait_timeout   | 50    |
| innodb_rollback_on_timeout | OFF   |
| interactive_timeout        | 28800 |
| net_read_timeout           | 30    |
| net_write_timeout          | 60    |
| slave_net_timeout          | 3600  |
| table_lock_wait_timeout    | 50    |
| wait_timeout               | 28800 |
+----------------------------+-------+
10 rows in set (0.00 sec)

其中的 interactive_timeout  就是管这个的, 28800秒等于8小时,将其改大即可:

mysql> set global interactive_timeout=86400;

当然其他参数也可以这样改。