最近用python实现了web服务遇到了一个问题,第一天可以正常请求服务,第二天就可以请求就失败,重启服务后,又能正常访问,查看日志发现如下报错内容
pymysql.err.OperationalError: (2006, "MySQL server has gone away (ConnectionResetError(104, 'Connection reset by peer'))")
查了资料才知道,原来数据库默认的连接时间默认是8小时,超过8小时,就会自动断开数据库连接,而且不会为原连接自动恢复。
解决这个问题有两种方法:
# 获取数据库连接
def get_conn():
global conn
global cur
if conn is not None:
try:
conn.ping(True)
return conn
except Exception as e:
logging.exception(e)
try:
conn = pymysql.Connect(host='主机名', user='用户名', password='密码', database='数据库', port=3306, charset='utf8mb4', )
return conn
except Exception as e:
logging.exception(e)
# 查询数据
querystr ="SELECT * FROM t_user"
get_conn()
cur.execute(querystr)
conn.commit()