我有以下数据库连接代码,最初我没有多次尝试的while循环,但后来我认为在真正失败之前进行多次尝试会更好。我的问题是,实现这一目标的最佳方法是什么?我应该使用计时器吗?并在再次尝试之前睡一会?
while connect_attempts < 3:
try:
# dbname cann't have hyphen but host name can'
db_name = self.language.replace('-','_') + 'db'
print 'Connecting to DB ' + db_name
logging.info("Connecting to Toolserver MySql Db: " + db_name)
self.dbConnection = MySQLdb.connect(
db=db_name,
host=self.language + "someserver_name.org",
read_default_file=os.path.expanduser("~/.my.cnf"))
logging.info("Connection Successful: " + str(self.dbConnection))
self.dbCursor = self.dbConnection.cursor(cursors.DictCursor)
except MySQLdb.Error, e:
logging.error("Unable to establish connection MySQL ERROR - attempt-" + str(connect_attempt), e.value)
connect_attempts += 1