我正在使用MySQL PDO来处理数据库查询和所有。但在大多数情况下,MySQL连接都会消失。因此,我在PDO中查找,它将检查数据库连接是否存在,如果不存在,则需要连接数据库以继续查询执行。
我是MySQL pdo的新手,我不知道如何处理这种情况。如果有人对此提出建议,那就更好了。
发布于 2015-02-24 06:50:58
我试着为同样的问题找到一个解决方案,我找到了下一个答案:
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)一直在通过UNIX套接字回复“本地主机,”甚至在停止mysqld之后“。
发布于 2014-04-23 20:41:45
您可以像这样使用:
# 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;
}https://stackoverflow.com/questions/23244462
复制相似问题