問題描述
我使用 MySQL PDO 來處理數據庫查詢等.但大多數時候,MySQL 連接消失了.所以我正在查看 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.
我是 MySQL pdo 的新手,我不知道如何處理這種情況.如果有人對此提出建議會更好.
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.
推薦答案
我試圖為同樣的問題尋找解決方案,但我找到了下一個答案:
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);
}
}
完整故事在這里:https://terenceyim.wordpress.com/2009/01/09/adding-ping-function-to-pdo/
其他人想使用 PDO::ATTR_CONNECTION_STATUS,但他發現:$db->getAttribute(PDO::ATTR_CONNECTION_STATUS)
即使在停止 mysqld 之后,仍然繼續回復Localhost via UNIX socket".
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".
這篇關于我如何 ping MySQL 數據庫并使用 PDO 重新連接的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!