I solved this problem by creating a function that wraps the cursor.execute()
method since that's what was throwing the MySQLdb.OperationalError
exception. The other example above implies that it is the conn.cursor()
method that throws this exception.
import MySQLdb
class DB:
conn = None
def connect(self):
self.conn = MySQLdb.connect()
def query(self, sql):
try:
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
db = DB()
sql = "SELECT * FROM foo"
cur = db.query(sql)
# wait a long time for the Mysql connection to timeout
cur = db.query(sql)
# still works
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…