How do i ping the MySQL db and reconnect using PDO

后端 未结 2 891
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 18:00

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 co

相关标签:
2条回答
  • 2020-12-17 18:44

    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".

    0 讨论(0)
  • 2020-12-17 18:48

    You can use like this:

    # 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;
    }
    
    0 讨论(0)
提交回复
热议问题