2013-03-05 59 views
0

「查詢過程中丟失連接到MySQL服務器的」我使用如何捕捉特定的錯誤

def mysql_handling(string): 
    global cursor 
    while True: 
     try: 
      cursor.execute(string) 
      if 'SELECT' not in string: 
       db.commit() 
      break 
     except MySQLdb.MySQLError: 
      cursor.close() 
        print 'something went wrong!!' 
      time.sleep(1) 
      cursor = get_cursor() 

如果要在連接失敗重新進行查詢,但我ONLY要重新連接時,我有錯誤「查詢期間與MySQL服務器失去連接」。 (否則mysql_handling函數進入無限循環)

那麼我應該用什麼來代替'除了MySQLdb.MySQLError:'

回答

1

this page它似乎是你不能真正捕捉異常,那就是具體的,但需要去接近你可以(OperationalError)並檢查errno的exact error code;

except MySQLdb.OperationalError as err: 

    if err.errno == errorcode.CR_SERVER_LOST: 
     # This is the error you're looking for 
    else: 
     # This is not the error you're looking for 
     raise   
+0

謝謝你的回答! – Lazykiddy 2013-03-05 13:35:20

1

而不是True時,您可以嘗試連接並再次提交除了塊。

def mysql_handling(string): 
    global cursor 
    try: 
     cursor.execute(string) 
     if 'SELECT' not in string: 
      db.commit() 
    except MySQLdb.MySQLError: 
     cursor.close() 
       print 'something went wrong!!' 
     time.sleep(1) 
     cursor = get_cursor() 
     cursor.execute(string) 
     if 'SELECT' not in string: 
      db.commit() 
    finally: 
      if cursor: 
       cursor.close() 

或U可以保持重試的最大數量說像5

+0

我限制了像你說的重試次數,謝謝! – Lazykiddy 2013-03-05 13:26:16