这几天自己写了一个python天天薅某个境外网站的羊毛,执行过程中会往mysql中写入数据。昨天代码跑了一下午突然报错了:
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query ([WinError 10054])
原因是MySQL持久化链接保持时间为8小时(28800秒),过期后断开连。如果数据库没有新建连接,就会报这个错误。[参考文献]
结合参考文献,修改自己的数据库工具类:
#! /usr/bin/python
# coding=utf-8
try:
import MySQLdb as MySQL
except:
#python3不支持MySQLdb
import pymysql as MySQL
import time
class mysql:
def __init__(self,
host = '',
user = '',
passwd = '',
db = '',
port = 3306,
charset = 'utf8'):
self.host = host
self.host = host
self.user = user
self.passwd = passwd
self.db = db
self.port = port
self.charset= charset
self.conn = None
self._conn()
def _conn(self):
try:
self.conn = MySQL.Connection(host = self.host, user = self.user, passwd = self.passwd, db = self.db, port = self.port , charset = self.charset)
print("数据库连接成功")
return True
except Exception as e:
print("数据库连接失败:"+str(e))
return False
#通过ping()实现数据库的长连接
def _reConn(self,num = 28800,stime = 3):
_number = 0
_status = True
while _status and _number <= num:
try:
#ping校验连接是否异常
self.conn.ping()
_status = False
except:
print("数据库断开连接,重连")
if self._conn()==True:
_status = False
break
_number +=1
time.sleep(stime)
def querry(self,sql):
try:
self._reConn()
self.cursor = self.conn.cursor()
self.cursor.execute(sql)
results = self.cursor.fetchall()
self.cursor.close()
return results;
except Exception as e:
print("querry异常:"+str(e))
return None;
def insert(self,sql,param):
try:
self._reConn()
self.cursor = self.conn.cursor()
res = self.cursor.execute(sql,param);
self.conn.commit();
self.cursor.close()
return res;
except Exception as e:
self.conn.rollback();
print("insert异常:"+str(e))
return False;
def close(self):
self._reConn()
self.conn.close();