如何在SQLite中显示SQL错误? [英] How to show SQL errors in SQLite?
问题描述
在PHP中使用SQLite(因此使用PDO),我有这样的代码:
Using SQLite in PHP (thus using PDO), I have this code:
try {
$db = new PDO("sqlite:C:\Program Files\Spiceworks\db\spiceworks_prod.db");
echo "Done.<br /><b>";
$query = "SELECT id FROM Devices LIMIT 5";
echo "Results: ";
$result = $db->query($query);
while ($row = $result->fetchArray()) {
print_r($row)."|";
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
但是这不会打印出来自SQL的任何数据。我知道数据库中有数据,连接有效。如果我将查询更改为:
But that does not print out any data from the SQL. I know the database has data in it and the connection is valid. If I change the query to say:
$query = "SELECT BLAHid FROM FakeDevices LIMIT 5";
没有任何变化。 SQL中没有任何内容再次打印出来,即使这显然是一个无效的SQL查询,我也看不到任何错误。
Nothing changes. Nothing from SQL gets printed out again, and I see no errors even though this is clearly an invalid SQL query.
在这两种情况下,完成和结果打印好了。如何打印SQL错误,如查询无效?
In both situations, the "Done" and "Results" gets printed out okay. How can I print out SQL errors, like if the query is invalid?
推荐答案
您需要告诉PDO抛出异常。您可以通过在连接到数据库后添加以下行来执行此操作:
You need to tell PDO to throw exceptions. You can do that by adding the following line after you connect to the database:
$db = new PDO("sqlite:C:\Program Files\Spiceworks\db\spiceworks_prod.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
这样你可以捕获所有异常,除了第一行可能存在的问题,数据库连接本身。
That way you can catch all exceptions except for a possible problem with the first line, the database connection itself.
这篇关于如何在SQLite中显示SQL错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!