如何启用 MySQL 客户端与 MySQLdb 的自动重新连接?

2021-11-20 00:00:00 python mysql

我发现了 PHP 的方法:

I came across PHP way of doing the trick:

my_bool reconnect = 1;
mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);

但没有使用 MySQLdb (python-mysql).

but no luck with MySQLdb (python-mysql).

谁能给个提示?谢谢.

推荐答案

我通过创建一个包装 cursor.execute() 方法的函数解决了这个问题,因为这就是抛出 MySQLdb.OperationalError 异常.上面的另一个示例暗示是 conn.cursor() 方法引发了此异常.

I solved this problem by creating a function that wraps the cursor.execute() method since that's what was throwing the MySQLdb.OperationalError exception. The other example above implies that it is the conn.cursor() method that throws this exception.

import MySQLdb

class DB:
  conn = None

  def connect(self):
    self.conn = MySQLdb.connect()

  def query(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

db = DB()
sql = "SELECT * FROM foo"
cur = db.query(sql)
# wait a long time for the Mysql connection to timeout
cur = db.query(sql)
# still works

相关文章