I have a mySQL db running on a docker container and flask/python running on another docker container. I am connecting to the db using mysql.connector.connect.
我在一个码头容器上运行一个MySQL数据库,在另一个码头容器上运行flASK/python。我正在使用mysql.Connector.Connect连接到数据库。
All queries work perfectly. However, after a few hours (by observing the time elapsed, I believe 7-8 hours), the mySQL container automatically disconnects the connection.
所有查询都能完美地工作。然而,几个小时后(通过观察过去的时间,我相信是7-8小时),MySQL容器自动断开连接。
How do I reconnect the connection? Or is there a way to change the settings such that the connection is not automatically disconnected?
如何重新连接连接?或者,有没有办法更改设置,使连接不会自动断开?
I have tried cnx.close()
and cnx.reconnect()
. However, both these calls do not return and the the program does not execute further.
我已经尝试了cnx.lose()和cnx.reConnect()。但是,这两个调用都不会返回,程序也不会进一步执行。
更多回答
优秀答案推荐
This is the result of a MySQL default setting : interactive_timeout
After 28800 seconds (8 hours) of inactivity, the server closes the connection.
这是MySQL默认设置的结果:interactive_timeout在28800秒(8小时)的不活动之后,服务器关闭连接。
Option 1 : increase the timeout to meet your needs
In the MySQL container, set a new value via the my.cnf
file
在MySQL容器中,通过my.cnf文件设置一个新值
[mysqld]
interactive_timeout = xxxxx
Option 2 : use a connection pool
In your program, use connection pooling. It will handle disconnections for you.
在您的程序中,使用连接池。它将为您处理断开连接的问题。
Pros and cons
|
Advantage |
Disadvantage |
Option 1 |
No further coding |
Might block the MySQL server over time (1) |
Option 2 |
Better usage of server's resources |
Requires an effort to change the program |
(1) : depending on the concurrency in your program, keeping connections open could cause the server to reach the maximum number of simultaneous connections allowed.
(1):根据程序中的并发性,保持连接打开可能会导致服务器达到允许的最大并发连接数。
更多回答
我是一名优秀的程序员,十分优秀!