Reconnecting MySQL on timeout

后端 未结 3 888
陌清茗
陌清茗 2020-12-31 16:04

I have a Python program which runs on background for weeks, and does database queries every once in a while. For that, I am using the ORM peewee (version 2.2.1). I am using

相关标签:
3条回答
  • 2020-12-31 16:16

    I have resolved this issue.

    My solution is use mysql connection pool PooledMySQLDatabase from playhouse.pool module.

    please read: https://github.com/coleifer/peewee/issues/239

    from peewee import *
    from playhouse.pool import *
    
    0 讨论(0)
  • 2020-12-31 16:30

    You have to catch the exception and based on which error, reconnect or to do something else. Whether it is a connection time out, or a network problem or the MySQL had to be restarted.

    The below (pseudoish) code shows how you could do that, but there is more to it. You'll want to try a few times and then bail out, or maybe try every 2 minutes or so.

    while True:
        try:
            # do your database stuff
        except peewee.OperationalError as exc:
            # Oops! We have to try to reconnect
    

    Does not really matter whether you use an ORM or not. However, an ORM might offer this functionality.

    0 讨论(0)
  • 2020-12-31 16:35

    I had the same problem and for peewee using MySQLdb I got the following solution when initialize the MySQL database instance:

    db = MySQLDatabase(db_name, user=db_username, passwd=db_password, host=db_host, port=db_port)
    db.get_conn().ping(True)
    

    where for the ping function there is:

    Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted.

    This function can be used by clients that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary.

    New in 1.2.2: Accepts an optional reconnect parameter. If True, then the client will attempt reconnection. Note that this setting is persistent. By default, this is on in MySQL<5.0.3, and off thereafter.

    Non-standard. You should assume that ping() performs an implicit rollback; use only when starting a new transaction. You have been warned.

    in the db.get_conn().ping.__doc__. Mind that db.get_conn().ping(True) has to be used if you create another connection again. So if you reconnect (through db.connect() for example) you must repeat the ping.

    0 讨论(0)
提交回复
热议问题