【问题标题】:Reconnecting on MySQL Server Has Gone Away在 MySQL 服务器上重新连接已消失
【发布时间】:2011-10-15 04:47:04
【问题描述】:

我如何修改这个类来捕捉 MySQL Server Goes Away 的异常并重新连接?

<?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;
}
}

【问题讨论】:

  • 抓住枪子的脖子,把他带回家。但说真的,我不应该通过重新初始化 PDO 对象来重新连接吗?我认为的关键问题是如何设置一个钩子来捕获查询和执行方法。

标签: php mysql error-handling pdo


【解决方案1】:

您可能需要像这样创建自己的课程

  1. __construct 中删除try/except
  2. 然后像这样连接到您的数据库:
$conn = null;
$限制 = 10;
$计数器 = 0;
而(真){
  尝试 {
    $conn = DBConn();
    休息;
  }
  捕获(异常 $e){
    $conn = 空;
    $计数器++;
    if ($counter == $limit)
      抛出$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);
}

【讨论】:

  • 但这不是捕获所有异常吗?我们不应该只抓MySQL Server Has Gone Away吗??
  • @Bludream 是的,我同意,首先,您应该只捕获 PDOException(其他异常类型不是我们的问题)。其次,我认为 PDOexceptions 上的代码设置为 SQL 服务器生成的错误代码。您可以检查 SQL Server 的特定代码是否已消失(不过您必须自己查找)。最后,您应该在尝试重新连接之前睡觉,因为您只会用连接请求敲击服务器。如果服务器处于临时启动状态(例如,它正在启动过程中),它可能会拒绝连接,但会在一秒钟后接受它们。
猜你喜欢
  • 2016-05-17
  • 2010-12-12
  • 2018-03-21
  • 2020-12-14
  • 2019-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多