2013-03-05 58 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