我正在使用
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:'?
答案 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