`

解决mysql中的OperationalError: (2006, 'MySQL server has gone away')

阅读更多

   这两天在python中用MySQLdb module操作数据库,碰到了如下错误信息:

OperationalError: (2006, 'MySQL server has gone away'), 发生在一个长时间的读操作之中。

看起来是connection在idle timeout后被关闭了。

 

 

之后找到了解决方案,就是碰到 AttributeError, MySQLdb.OperationalError之后就重新连接并再次执行上次的sql语句。

 

 

封装的代码如下:

 

class DB:
  conn = None
  cursor = None
  def connect(self):
    self.conn = MySQLdb.connect (host = global_srcDB_Host,
                             user = global_srcDB_User,
                             passwd = global_srcDB_PWD,
                             db = global_srcDB_DB)

  def execute(self, sql):
    try:
      cursor = self.conn.cursor()
      cursor.execute(sql)
    except (AttributeError, MySQLdb.OperationalError):
      self.connect()
      cursor = self.conn.cursor()
      cursor.execute(sql)
    return cursor

  def close(self):
    if(self.cursor):
      self.cursor.close()
    self.conn.commit()
    self.conn.close()

 

使用如下:

db = DB()    

cursor = db.execute (sql)

db.close()  

 

至此,问题解决。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics