有時候PDO物件連線,然後程式在處理大量資料時,Mysql等太久最後timeout斷線了

這時執行query就會需到Mysql Server has gone away的錯誤 (uncaught exception)

一昧的加大timeout,不如直接Catch這個Exception

範例程式如下:

失敗後重連線一次

 /** 
截取我的程式的一部分
$this->Connect是我的PDO物件*/

function executeQuery($query) {
$sth = $this->Connect->prepare($query);  try {
$sth->execute($params);//執行query
 } catch (PDOException $e) {

/** 這邊會抓到PDO的Exception */ $this->connect(); //重新連線
/** 這邊也可以用遞迴 $this->executeQuery($query)*/   $sth=$this->Connect->prepare($query);   $sth->execute($params);

}
.
(略)
.
.
}

補充,你可以判斷Exception的種類看是不是真的是Mysql Server has gone away,然後做是否重連線執行query的決定。

當然你也可以設retry,用遞迴的方式把retry的次數繼續往下帶:

 

 /** 
遞廻方式
*/

function executeQuery($query, $retry = 3) {

if ($retry == 0) {
return false;
}
$sth = $this->Connect->prepare($query); try {
$sth->execute($params);//執行query
 } catch (PDOException $e) {

/** 這邊會抓到PDO的Exception */
$this->connect(); //重新連線
  $sth=$this->executeQuery($query, $retry--);

}
.
(略)
.
.
}

 

arrow
arrow

    Oscar 發表在 痞客邦 留言(0) 人氣()