如何捕获特定错误“在查询期间丢失与MySQL服务器的连接”

时间:2013-03-05 12:39:27

标签: python 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()

如果连接失败,请重试查询,但当“查询期间与MySQL服务器连接丢失”时,我想要重试连接。 (否则mysql_handling函数进入无限循环)

那么我应该使用什么而不是',除了MySQLdb.MySQLError:'

2 个答案:

答案 0 :(得分: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()

或者你可以保持最大重试次数,比如5。

答案 1 :(得分:1)

this page开始,您似乎无法捕捉到特定的异常,但需要尽可能接近(OperationalError)并检查{{3}的错误};

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