Python mysql (using pymysql) auto reconnect

前端 未结 4 1995
囚心锁ツ
囚心锁ツ 2021-02-07 14:08

I\'m not sure if this is possible, but I\'m looking for a way to reconnect to mysql database when the connection is lost. All the connections are held in a gevent queue but that

4条回答
  •  逝去的感伤
    2021-02-07 14:27

    Well, I've got the same problem in my application and I found a method on the PyMySQL documentation that pings to the server and check if the connection was closed or not, if it was closed, then it reconnects again.

    from pymysql import connect
    from pymysql.cursors import DictCursor
    
    # create the connection
    connection = connect(host='host', port='port', user='user', 
                         password='password', db='db', 
                         cursorclass=DictCursor)
    
    # get the cursor
    cursor = connection.cursor()
    
    # if the connection was lost, then it reconnects
    connection.ping(reconnect=True)      
    
    # execute the query
    cursor.execute(query)
    

    I hope it helps.

提交回复
热议问题