Python mysql (using pymysql) auto reconnect

前端 未结 4 1990
囚心锁ツ
囚心锁ツ 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:30

    the logic is quite simple, if connection close then try to reconnect for several times in this case I use max tries for 15 times to reconnect or ping.

    import pymysql, pymysql.cursors
    conn = pymysql.connect(
                             host=hostname,
                             user=username,
                             password=password,
                             db=dbname,
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor,
                             )
    cursor = conn.cursor()
    # you can do transactions to database and when you need conn later, just make sure the server is still connected
    if conn.open is False:
       max_try = 15
       try = 0
       while conn.open is False:
           if try < max_try:
               conn.ping() # autoreconnect is true by default
           try +=1
    
    # check the conn again to make sure it connected
    if conn.open:
        # statements when conn is successfully reconnect to the server
    else:
        # it must be something wrong : server, network etc
    

提交回复
热议问题