我正在使用Python和mySQL,並且查詢之間有很長時間的滯後。結果,我得到一個'MySQL連接已經消失'的錯誤,即wait_timeout超出。Python:MySQL:處理超時
這已經在例如在 Gracefully handling "MySQL has gone away"
但這並不具體回答我的查詢。
所以我的方法來處理這個 - 我已經包裹我所有的SQL的方法執行語句 -
def __execute_sql(self,sql,cursor):
try:
cursor.execute(sql)
except MySQLdb.OperationalError, e:
if e[0] == 2006:
self.logger.do_logging('info','DB', "%s : Restarting db" %(e))
self.start_database()
我在調用該查詢的代碼的幾個地方。關鍵是,我也有幾個遊標,因此該方法調用看起來喜歡 -
self.__execute_sql(sql,self.cursor_a)
self.__execute_sql(sql,self.cursor_b)
等
我需要一種方法分貝啓動後優雅地重新執行查詢。 if語句我可以換的電話在,並重新執行所以這將是
def __execute_sql(self,sql,cursor):
try:
cursor.execute(sql)
return 1
except MySQLdb.OperationalError, e:
if e[0] == 2006:
self.logger.do_logging('info','DB', "%s : Restarting db" %(e))
self.start_database()
return 0
然後
if (self.__execute_sql(sql,self.cursor_a) == 0):
self.__execute_sql(sql,self.cursor_a)
但這是笨重。有一個更好的方法嗎? 謝謝!
運行查詢被認爲是反模式是浪費資源和不可靠之前執行ping:https://www.percona.com/blog/2010/05/05/checking-for-a-實時數據庫連接認爲有害/ –