mysql 连接闪断自动重连的方法(用在后台运行中的PHP代码)
当mysql断开连接 $_instance这个还是有值得 所以会报错 MySQL server has gone away 这个地方需要捕捉异常才可以或许到
需要 清空连接 $_instance 这样就可以重新连接 就会报错了
<?php
// 数据库操作类
class DB{// 保存数据库连接
private static $_instance = null;// 连接数据库
public static function get_conn($config){
if(isset(self::$_instance) && !empty(self::$_instance)){
return self::$_instance;
}$dbhost = $config['host'];
$dbname = $config['dbname'];
$dbuser = $config['user'];
$dbpasswd = $config['password'];
$pconnect = $config['pconnect'];
$charset = $config['charset'];$dsn = "mysql:host=$dbhost;dbname=$dbname;";
try {
$h_param = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //设置错误级别
);
if ($charset != '') {
$h_param[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $charset; //设置默认编码
}
if ($pconnect) {
$h_param[PDO::ATTR_PERSISTENT] = true; //是否是长连接
}
$conn = new PDO($dsn, $dbuser, $dbpasswd, $h_param);} catch (PDOException $e) {
throw new ErrorException('Unable to connect to db server. Error:' . $e->getMessage(), 31);
}self::$_instance = $conn;
return $conn;
}// 执行查询
public static function query($dbconn, $sqlstr, $condparam){
$sth = $dbconn->prepare($sqlstr);
try{
$sth->execute($condparam);
} catch (PDOException $e) {
echo $e->getMessage().PHP_EOL;
self::reset_connect($e->getMessage()); // 出错时调用重置连接
}
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
return $result;
}// 重置连接
public static function reset_connect($err_msg){
if(strpos($err_msg, 'MySQL server has gone away')!==false){
self::$_instance = null;
}
}}
?>
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/4050.html