You can use a for
loop with an else
clause for maximum effect:
conn = MySQLdb.connect(host, user, password, database)
cursor = conn.cursor()
for n in range(3):
try:
cursor.execute(query)
except MySQLdb.Error, e:
print "MySQL Error %d: %s" % (e.args[0], e.args[1])
else:
rows = cursor.fetchall()
for row in rows:
# do something with the data
break
else:
# All attempts failed, raise a real error or whatever
The key is to break out of the loop as soon as the query succeeds. The else
clause will only be triggered if the loop completes without a break
.