Reconnecting MySQL on timeout

后端 未结 3 889
陌清茗
陌清茗 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: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.

提交回复
热议问题