[英]How can I check a PDO MySQL connection for errors BEFORE I run a query?
My scripts are getting quite riddled with forked processes in a lot of different functions. 我的脚本在很多不同的功能中都充满了分叉的进程。 Whenever
pcntl_fork()
is called, all MySQL connections are lost. 每当
pcntl_fork()
,所有MySQL连接都将丢失。 If I run a query on a PDO MySQL connection I get the error "MySQL server has gone away"
. 如果我在PDO MySQL连接上运行查询,我会收到错误
"MySQL server has gone away"
。
The problem is that this error only shows up in PDO::errorinfo()
after a failed query execution. 问题是在查询执行失败后,此错误仅显示在
PDO::errorinfo()
。 I would like to be able to detect if the MySQL server "has gone away" before I try to run a query. 在尝试运行查询之前,我希望能够检测MySQL服务器是否“已经消失”。 That way I could create a PDO wrapper that makes a new connection for me in such situations.
这样我就可以创建一个PDO包装器,在这种情况下为我创建一个新的连接。
Any ideas? 有任何想法吗?
FYI: this has been reported as a bug several times 1 , 2 , 3 with no fix so far (5.3.14). FYI:这已被报告为一个bug几次1 , 2 , 3 ,无修复至今(5.3.14)。 The only solution is to do a new connection each time after forking a child, and also set PDO::ATTR_PERSISTENT => false
唯一的解决方案是每次分叉子项后都要建立一个新连接,并设置PDO :: ATTR_PERSISTENT => false
I give you 2 methods by example (similar in some ways) : 我通过示例给出了2个方法(在某些方面类似):
Example 1 : 例1:
$sql = 'SELECT count(*) FROM `TABLE`;';
for ($i = 1; $i <= 2; $i++) {
try {
$nb = $pdo->query($sql)->fetchColumn();
if (is_int($nb)) {
// OK
break;
}
} catch (PDOException $e) {
//Oups
if ($i == 1) {
// First time ? retry
$pdo = new PDO($dsn, $user, $password);
} else {
// Second time, KO
$nb = "(unknown)";
echo 'PDO Connection failed: ' . $e->getMessage().'. ';
}
}
}
Example 2 : 例2:
// check
try {
$pdo->query('select 1;')
//OK
} catch (PDOException $e) {
//Oups => reconnect
$pdo = new PDO($dsn, $user, $password);
}
// Should be good
$sql = 'SELECT count(*) FROM `TABLE`;';
$nb = $pdo->query($sql)->fetchColumn();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.