zoukankan      html  css  js  c++  java
  • mysql 连接闪断自动重连的方法(用在后台运行中的PHP代码)

    mysql 连接闪断自动重连的方法(用在后台运行中的PHP代码)
    当mysql断开连接 $_instance这个还是有值得 所以会报错 MySQL server has gone away 这个地方需要捕捉异常才可以或许到
    需要 清空连接 $_instance 这样就可以重新连接 就会报错了
    <pre>
    <?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;
    }
    }

    }
    ?>
    </pre>

  • 相关阅读:
    使用OPC的方式去连接PLC进行AB SLC-5_04数据的采集
    pytest:conftest.py运行细节一则
    《数据结构与算法》和《设计模式》之开门见山篇
    C语言真正的编译过程
    外挂原理之植物大战僵尸
    ORACLE数据库创建动态表
    JS中事件绑定问题
    由 “无法使用从远程表选择的 lob 定位符” 错误而引导出来的一系列问题解决方案
    安装JDK,配置环境变量有感
    MSSQL 常见故障处理
  • 原文地址:https://www.cnblogs.com/newmiracle/p/11865334.html
Copyright © 2011-2022 走看看