Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
951 views
in Technique[技术] by (71.8m points)

php - How do i ping the MySQL db and reconnect using PDO

I am using MySQL PDO for handling database querying and all. But most of the time, the MySQL connection is gone away. So i am looking in the PDO that will check if the db connection is exists or not and if it is not exit, then i need to connect the database to continue the query execution.

I am new to the MySQL pdo and i do not know how to handling this situation. It would be better if anybody suggest on this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I tried to find a solution for the same problem and I found the next answer:

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

Full story here: https://terenceyim.wordpress.com/2009/01/09/adding-ping-function-to-pdo/


Somebody else was thinking to use PDO::ATTR_CONNECTION_STATUS, but he figured out that: "$db->getAttribute(PDO::ATTR_CONNECTION_STATUS) keeps replying “Localhost via UNIX socket” even after stopping mysqld".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...