简体   繁体   中英

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

My question is about reconnecting to MySQL server if any error encounters.

I am connecting to the MySQL server in Flask:

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

and for the query using the cursor as well: Flask route code:

@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)

I want to reconnect to db when I get the error:

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

Please help me find the solution for this error.

How to reconnect to the database when any error encounters.

Thanks in advance!

Looks like you are using a single connection forever. Try to create a new connection every time and close it once the required queries are run. This issue can be avoided through this.

Setting pool_pre_ping=True when calling create_engine() seems to have helped quite a bit in my case.

Example:

engine = create_engine(db_connection, pool_pre_ping=True)

From the SQLAlchemy docs on pool_pre_ping :

"If True will enable the connection pool “pre-ping” feature that tests connections for liveness upon each checkout."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM