pyMysqL.err.OperationalError: (2013,'Lost connection to MysqL server during query')
pyMysqL.err.InterfaceError: (0,'')
错误原因:
MysqL> SHOW SESSION VARIABLES LIKE 'wait_timeout';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout | 28800 |
+---------------+-------+
解决思路:
调用前判断连接是否有效,如果有效继续,无效创建连接。
class DataBase():
"""数据库类"""
def __init__(self,host='localhost',user='root',pw='password',db='test'):
self.con = pyMysqL.connect(host,user,pw,db)
self.cur = self.con.cursor()
# 方法1:
def _reCon (self):
""" MysqLdb.OperationalError异常"""
# self.con.close()
while True:
try:
self.con.ping()
break
except OperationalError:
self.con.ping(True)
# 方法2:
def _reConn (self,num=28800,stime=3):
"""
校验数据库连接是否异常
num:8小时
stime:间隔3秒重连
"""
_number = 0
_status = True
while _status and _number <= num:
try:
self.con.ping() #cping 校验连接是否异常
_status = False
except:
if self.con == True: #重新连接,成功退出
_status = False
break
_number +=1
time.sleep(stime) #连接不成功,休眠3秒钟,继续循环,直到循环8小时
def insert_visitor_info(self,time,device_id,room_id):
"""插入访客请求信息"""
self._reCon()
# self._reConn()
with self.con:
sql = "INSERT INTO visitor(time,room_id) VALUES(%s,%s,%s)"
self.cur.execute(sql,(time,room_id))
if __name__ == '__main__':
db = DataBase()
db.insert_visitor_info('2019-03-31 17:57:08','8b417cb51268','312')