2013-03-19 61 views
0

我有以下的數據庫連接代碼,最初我沒有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 

回答

0

我覺得默認的參數是沒有超時指示here

您可以將參數設置超時,如。 10秒後,此連接 將被丟棄,並且將嘗試建立連接。

+0

指向原始來源的鏈接更可取:http://mysql-python.sourceforge.net/MySQLdb.html#functions-and-attributes – RandomSeed 2013-03-20 15:02:42

0

根據Sumeet的建議,您應在撥打MySQLdb.connect()時設置超時時間。但連接也可能由於其他許多原因而失敗(例如服務器立即拒絕連接,因爲它太忙了,或者它處於某種維護模式 - 不是現實生活中的例子,只是想象)

您自己的循環應該也包括很短的延遲。我會在你的異常處理程序中延遲執行幾秒鐘。