Python mysql (using pymysql) auto reconnect

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

    The easiest way is to check the connection right before sending a query.

    You can do this by creating a small class that contains two methods: connect and query:

    import pymysql
    import pymysql.cursors
    
    class DB:
        def connect(self):
            self.conn = pymysql.connect(
                                 host=hostname,
                                 user=username,
                                 password=password,
                                 db=dbname,
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor,
                                 port=3306)
    
        def query(self, sql):
            try:
                cursor = self.conn.cursor()
                cursor.execute(sql)
            except pymysql.OperationalError:
                self.connect()
                cursor = self.conn.cursor()
                cursor.execute(sql)
            return cursor
    
    db = DB()
    

    Now, whenever you send a query using db.query("example SQL") the request is automatically prepared to encounter a connection error and reconnects using self.connect() if it needs to.

    Remember: This is a simplified example. Normally, you would want to let PyMySQL help you escape special characters in your queries. To do that, you would have to add a 2nd parameter in the query method and go from there.

提交回复
热议问题