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

查看:111
本文介绍了如何启用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).

有人可以提供线索吗?谢谢.

Can anybody please give a clue? Thanks.

推荐答案

我通过创建一个包装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天全站免登陆