使用PDO运行多个查询时,如何出现错误? [英] How can I get an error when running multiple queries with PDO?
本文介绍了使用PDO运行多个查询时,如何出现错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用PDO运行多个查询.如果第二个查询失败,则抛出Exception.
I'm running multiple queries using PDO. If the second query fails, now Exception is thrown.
$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "
DELETE FROM car;
INSERT INTO car(name, type) SELECT name, from FROM vehicle;
";
try {
$db->exec($sql);
}
catch (PDOException $e)
{
echo $e->getMessage();
die();
}
上面的代码执行时不会抛出异常.
The above code executes without throwing an exception.
如何确保所有查询都已成功运行?如何检查哪些查询失败?
How can I make sure that all queries have run successfully? How can I check which queries have failed?
P.S.我正在使用PDO多重查询来运行MySQL转储,但是任何有效的.sql文件都可以使用.
推荐答案
我在使用准备好的语句时找到了答案.遍历所有行集之后,我可以使用$stmt->errorInfo()
检查执行的最后一个查询是否引起了错误.
I found the answer in using a prepared statement. After looping through all rowsets, I can check if the last query executed caused an error using $stmt->errorInfo()
.
$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
$sql = "
DELETE FROM car;
INSERT INTO car(name, type) SELECT name, from FROM vehicle;
";
$stmt = $db->prepare($sql);
$stmt->execute();
$i = 0;
do {
$i++;
} while ($stmt->nextRowset());
$error = $stmt->errorInfo();
if ($error[0] != "00000") {
echo "Query $i failed: " . $error[2];
die();
}
这篇关于使用PDO运行多个查询时,如何出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文