mysqldb 默认为8个小时为自动断开间隔时间,如何解决这个问题:
(1)mysqldb提供了一个方法采用类似:
try:
conn.ping()
except Excption,e: #实际对应的 MySQLdb.OperationalError 这个异常
conn = new conn
解决方案代码:
def executeSQL(self,sql=""):
try:
self.conn.ping()
except Exception,e:
self.log.error("Msql出了问题")
self.log.error(str(e))
while True:
try:
self.conn = MySQLdb.connect(self.config.get('mysql_server'),self.config.get('mysql_user'),self.config.get('mysql_pass'),self.config.get('mysql_db_name'),connect_timeout=60,compress=True,charset="UTF8")
break
except Exception,e:
self.log.error("尝试重连接失败")
time.sleep(2)
continue
self.cursor=self.conn.cursor()
try:
self.cursor.execute(sql)
self.conn.commit()
return 1
except Exception,e:
self.log.error(str(e))
return 0
(2)tonaldb解决方法,if now time - 起始连接时间 > 数据库自动断开间隔 则进行重连操作。
def _ensure_connected(self):
# Mysql by default closes client connections that are idle for
# 8 hours, but the client library does not report this fact until
# you try to perform a query and it fails. Protect against this
# case by preemptively closing and reopening the connection
# if it has been idle for too long (7 hours by default).
if (self._db is None or
(time.time() - self._last_use_time > self.max_idle_time)):
self.reconnect()
self._last_use_time = time.time()