How to enable MySQL client auto re-connect with MySQLdb?(如何启用 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 的自动重新连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何启用 MySQL 客户端与 MySQLdb 的自动重新连接?


- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- SQL 临时表问题 2022-01-01