Python: MySQL: Handling timeouts

后端 未结 3 1414
小鲜肉
小鲜肉 2021-01-13 09:02

I am using Python and mySQL, and there is a long lag between queries. As a result, I get an \'MySQL connection has gone away\' error, that is wait_timeout is exceeded.

3条回答
  •  無奈伤痛
    2021-01-13 09:50

    I tried Crasched's approach, which got me to a new OperationalError:

    OperationalError: (2013, 'Lost connection to MySQL server during query')

    My final solution was to first try the ping, and if another OperationalError was raised, to reconnect and recreate the cursor with the new connection, like so:

    try:
        self.connection.ping(True)
    except MySQLdb.OperationalError:
        self.connection = MySQLdb.connect(
            self.db_host,
            self.db_user,
            self.db_passwd,
            self.db_dbase,
            self.db_port)
        # reconnect your cursor as you did in __init__ or wherever    
        self.cursor = self.connection(
            MySQLdb.cursors.DictCursor)
    

    Back in business!

    Python 2.7, MySQL 5.5.41

提交回复
热议问题