我们在使用mysql服务的时候,正常情况下,mysql的设置的timeout是8个小时(28800秒),也就是说,如果一个连接8个小时都没有操作,那么mysql会主动的断开连接,当这个连接再次尝试查询的时候就会报个”MySQL server has gone away”的误,但是有时候,由于mysql服务器那边做了一些设置,很多情况下会缩短这个连接timeout时长以保证更多的连接可用。有时候设置得比较变态,很短,30秒,这样就需要客户端这边做一些操作来保证不要让mysql主动来断开。
查看mysql的timeout
使用客户端工具或者Mysql命令行工具输入show global variables like ‘%timeout%’;就会显示与timeout相关的属性,这里我用docker模拟了一个测试环境。
mysql> show variables like '%timeout%'; +-----------------------------+----------+ | Variable_name | Value | +-----------------------------+----------+ | connect_timeout | 10 | | delayed_insert_timeout | 300 | | have_statement_timeout | YES | | innodb_flush_log_at_timeout |<div>本文来源gaodai.ma#com搞##代!^码@网3</div> 1 | | innodb_lock_wait_timeout | 50 | | innodb_rollback_on_timeout | OFF | | interactive_timeout | 30 | | lock_wait_timeout | 31536000 | | net_read_timeout | 30 | | net_write_timeout | 60 | | rpl_stop_slave_timeout | 31536000 | | slave_net_timeout | 60 | | wait_timeout | 30 | +-----------------------------+----------+ 13 rows in set
wait_timeout:服务器关闭非交互连接之前等待活动的秒数,就是你在你的项目中进行程序调用
interactive_timeout: 服务器关闭交互式连接前等待活动的秒数,就是你在你的本机上打开mysql的客户端,cmd的那种
使用pymysql进行查询
我在数据库里随便创建了一个表,插入两条数据
mysql> select * from person; +----+------+-----+ | id | name | age | +----+------+-----+ | 1 | yang | 18 | | 2 | fan | 16 | +----+------+-----+ 2 rows in set
我使用pymysql这个库对其进行查询操作,很简单
#coding:utf-8 import pymysql def mytest(): connection = pymysql.connect( host='localhost', port=3306, user='root', password='123456', db='mytest', charset='utf8') cursor = connection.cursor() cursor.execute("select * from person") data = cursor.fetchall() cursor.close() for i in data: print(i) cursor.close() connection.close() if __name__ == '__main__': mytest()
可以正确的得到结果
(1, ‘yang’, 18)
(2, ‘fan’, 16)
连接超时以后的查询
上面可以正常得到结果是由于当创建好一个链接以后,就立刻进行了查询,此时还没有超过它的超时时间,如果我sleep一段时间,看看什么效果。
#coding:utf-8 import pymysql import time def mytest(): connection = pymysql.connect( host='localhost', port=3306, user='root', password='123456', db='mytest', charset='utf8') cursor = connection.cursor() cursor.execute("select * from person") data = cursor.fetchall() for i in data: print(i) cursor.close() time.sleep(31) cursor = connection.cursor() cursor.execute("select * from person") data2 = cursor.fetchall() for i in data2: print(i) cursor.close() connection.close() if __name__ == '__main__': mytest()
这里进行了两次查询,因为我把mysql的wait_timeout设置了30秒,所以我在第一次查询之后停了31秒,目的让mysql服务主动的和我刚才创建的连接断开,得到的结果是
(1, 'yang', 18) (2, 'fan', 16) Traceback (most recent call last): File "F:/python/python3Test/mysqltest.py", line 29, in <module> mytest() File "F:/python/python3Test/mysqltest.py", line 22, in mytest cursor.execute("select * from person") ... ... File "C:\Python35\lib\site-packages\pymysql\connections.py", line 702, in _read_bytes CR.CR_SERVER_LOST, "Lost connection to MySQL server during query") pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query') Process finished with exit code 1