Python and Django OperationalError (2006, 'MySQL server has gone away')

后端 未结 12 1700
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 15:25

Original: I have recently started getting MySQL OperationalErrors from some of my old code and cannot seem to trace back the problem. Since it was working before, I thought

12条回答
  •  醉梦人生
    2020-12-14 16:23

    Check if you are allowed to create mysql connection object in one thread and then use it in another.

    If it's forbidden, use threading.Local for per-thread connections:

    class Db(threading.local):
        """ thread-local db object """
        con = None
    
        def __init__(self, ...options...):
            super(Db, self).__init__()
            self.con = MySQLdb.connect(...options...)
    
    db1 = Db(...)
    
    
    def test():
        """safe to run from any thread"""
        cursor = db.con.cursor()
        cursor.execute(...)
    

提交回复
热议问题