我有以下的數據庫連接代碼,最初我沒有while循環多次嘗試,但後來我認爲它更好,我做了多次嘗試,才真正失敗它。我的問題是,完成這個的最好方法是什麼?我應該使用timmer嗎?並在再次嘗試之前做一些睡眠?Python-Mysql:多次嘗試連接 - 最佳實踐
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
指向原始來源的鏈接更可取:http://mysql-python.sourceforge.net/MySQLdb.html#functions-and-attributes – RandomSeed 2013-03-20 15:02:42