pymysql.err.OperationalError: (2006, "MySQL server has gone away (TimeoutError(110, 'Connection tim



我的问题是,如果遇到任何错误,请重新连接到MySQL服务器。

我正在连接到Flask的MySQL服务器:

connection = pymysql.connect(host='host',
user='user',
connect_timeout= 31536000,
password='passwd',
db='db_name',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)

并且对于同样使用光标的查询:烧瓶路线代码:

@app.route("/chart", methods=['GET', 'POST'])
def chart():
try:
with connection.cursor() as cursor:
#line chart open tickets
query = "select createdDate,rootCause,requestId from db_name;"
df = pd.read_sql(query, connection)
print(df)
except pymysql.MySQLError as e:
print(e)

当我得到错误时,我想重新连接到数据库:

pymysql.err.OperationalError: (2006, "MySQL server has gone away (TimeoutError(110, 'Connection timed out'))")

请帮我找到这个错误的解决方案。

遇到任何错误时如何重新连接到数据库。

提前感谢!

看起来您永远都在使用一个连接。尝试每次创建一个新连接,并在运行所需查询后关闭它。这个问题可以通过这个来避免。

在调用create_engine()时设置pool_pre_ping=True似乎对我的情况有很大帮助。

示例:

engine = create_engine(db_connection, pool_pre_ping=True)

来自pool_pre_ping:上的SQLAlchemy文档

"如果为True,将启用连接池"预ping"功能,该功能在每次签出时测试连接的活跃度">

最新更新