如何ping MySQL数据库并使用PDO重新连接

Raj*_*aja 10 php mysql pdo

我使用MySQL PDO来处理数据库查询等等.但大多数时候,MySQL连接已经消失.所以我在PDO中查看数据库连接是否存在,如果它不是退出,那么我需要连接数据库以继续查询执行.

我是MySQL pdo的新手,我不知道如何处理这种情况.如果有人建议这样做会更好.

Cri*_*cău 8

我试图找到同样问题的解决方案,我找到了下一个答案:

class NPDO {
    private $pdo;
    private $params;

    public function __construct() {
        $this->params = func_get_args();
        $this->init();
    }

    public function __call($name, array $args) {
        return call_user_func_array(array($this->pdo, $name), $args);
    }

    // The ping() will try to reconnect once if connection lost.
    public function ping() {
        try {
            $this->pdo->query('SELECT 1');
        } catch (PDOException $e) {
            $this->init();            // Don't catch exception here, so that re-connect fail will throw exception
        }

        return true;
    }

    private function init() {
        $class = new ReflectionClass('PDO');
        $this->pdo = $class->newInstanceArgs($this->params);
    }
}
Run Code Online (Sandbox Code Playgroud)

全文:https://terenceyim.wordpress.com/2009/01/09/adding-ping-function-to-pdo/


其他人正在考虑使用PDO :: ATTR_CONNECTION_STATUS,但他发现:$db->getAttribute(PDO::ATTR_CONNECTION_STATUS)"即使在停止mysqld之后,仍然通过UNIX套接字"回复"Localhost".


Luc*_*que -3

你可以这样使用:

# connect to the database
try {
  $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
  $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

}
catch(PDOException $e) {
    echo "Connection error " . $e->getMessage() . "\n";
    exit;
}
Run Code Online (Sandbox Code Playgroud)

  • 问题询问如何 ping 并重新连接,而不是如何捕获连接错误! (2认同)