有时候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--);

}
.
(略)
.
.
}

 

相关文章