Django - OperationalError: (2006, 'MySQL server has gone away')

前端 未结 4 1346
陌清茗
陌清茗 2021-02-19 04:56

Bottom line first: How do you refresh the MySQL connection in django?

Following a MySQL server has gone away error I found that MySQL docum

4条回答
  •  孤独总比滥情好
    2021-02-19 05:40

    having the same issue. I need idea how to check connection state for MySQLdb connection in django. i guess it can be achieved by

    try:
        cursor.execute(sql)
    catch OperationalError:
        reconnect
    

    is anybody have a better idea?

    UPDATE

    my decision

    self.connection.stat()
    if self.connection.errno()!=0:
    

    check state of mysqldb connection if error recreate connection

    UPDATE AGAIN

    you also need to serve case if connection is close

    if self.connection.open:
        self.connection.stat()
    

    refresh connection is just recreating it

        db_settings = settings.DATABASES['mysql_db']
        try:
            self.connection = MySQLdb.connect(host=db_settings['HOST'],port=int(db_settings['PORT']),db=db_settings['NAME'],user=db_settings['USER'],passwd=db_settings['PASSWORD'])
        except MySQLdb.OperationalError, e:
            self.connection = None
    

提交回复
热议问题