如何启用 MySQL 客户端与 MySQLdb 的自动重新连接? [英] How to enable MySQL client auto re-connect with MySQLdb?

查看:40
本文介绍了如何启用 MySQL 客户端与 MySQLdb 的自动重新连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了 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

这篇关于如何启用 MySQL 客户端与 MySQLdb 的自动重新连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆