2011-07-28 28 views
6

如何修改此類以捕獲MySQL服務器走開的異常並重新連接?在MySQL服務器上重新連接已離去

<?php 
class DBConn 
{ 
private $conn; 

public function __construct($persistent = false) 
{ 
    try 
    { 
     $this->conn = new PDO("mysql:host=localhost;dbname=test", 'test', "hoollaahaoo"); 
     $this->conn->exec("SET CHARACTER SET utf8"); 
     $this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 
     if ($persistent) 
      $this->conn->setAttribute(PDO::ATTR_PERSISTENT, true); 
    } 
    catch(PDOException $e) 
    { 
     return $e->getMessage(); 
    } 
} 

public function getConn() 
{ 
    return $this->conn; 
} 
} 
+0

抓住兒子,把他帶回家。但是,嚴重的是,我不應該通過重新初始化PDO對象來重新連接嗎?我認爲的關鍵問題是如何設置鉤子來捕獲查詢和執行方法。 – HyderA

回答

3

你可能會需要讓自己的類像這樣的

  1. __construct
  2. 刪除try/except然後連接到您DB這樣的:
$conn = null; 
$limit = 10; 
$counter = 0; 
while (true) { 
    try { 
    $conn = DBConn(); 
    break; 
    } 
    catch (Exception $e) { 
    $conn = null; 
    $counter++; 
    if ($counter == $limit) 
     throw $e; 
    } 

}

編輯1

,但如果你說你的服務器消失了....然後可能是水木清華像槍的脖子的這個

protected function _connect($persistent = false) { 
$conn = null; 
$limit = 10; 
$counter = 0; 
while (true) { 
    try { 
     $this->conn = new PDO("mysql:host=localhost;dbname=test", 'test', "hoollaahaoo"); 
     $this->conn->exec("SET CHARACTER SET utf8"); 
     $this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 
     if ($persistent) 
      $this->conn->setAttribute(PDO::ATTR_PERSISTENT, true); 
} 
    catch (Exception $e) { 
    $conn = null; 
    $counter++; 
    if ($counter == $limit) 
     throw $e; 
    } 
} 

public function __construct($persistent = false) 
{ 
    $this->_connect($persistent); 
} 
+1

但是這不是所有的異常?我們不應該只抓住'MySQL服務器已經離開'了嗎? – azerafati

+1

@Bludream是的我同意,首先,你應該只捕獲PDOException(其他異常類型不是我們的問題)。其次,我相信PDOexceptions上的代碼被設置爲SQL服務器生成的錯誤代碼。你可以檢查SQL服務器的特定代碼已經消失了(儘管你必須自己去查看)。最後,在嘗試重新連接之前,您應該睡眠,因爲您只需連接請求就可以連接服務器。如果服務器處於臨時啓動狀態(例如正在啓動),則可能會拒絕連接,但稍後再接受它們。 – GordonM

相關問題