会将false返回的PDO execute()与抛出的异常相同吗? [英] will a false returned PDO execute() the same as the exception it thrown?
问题描述
根据要求,我重新格式化了以下问题:
As requested I reformat the question:
对于以下代码:
$newPDO=new PDO($DSN,$USER,$PASS);
$newPDO->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$SQL='SOME SQL STATEMENT MAYBE FAULTY';
try{
$Query=$newPDO->Prepare($SQL)
$Success=$Query->execute();
if(!$Success)
echo('A');
}
catch(PDOException $e)
{
echo('B');
}
问题是,是否可以看到A打印?
Question is, is it possible to see 'A' printed? Will the answer varies for different type of $SQL
like select or insert?
原始问题:
- 首先我将属性设置为PDO :: ATTR_ERRMODE,PDO :: ERRMODE_EXCEPTION,所以我认为当execute()遇到DB的错误,它应该抛出一个异常。
然后我意识到,如果这是真的,我可能甚至不必检查execute()的返回,只要抛出的异常与返回的false相同。我只需要从外面赶上。如果没有被捕获,查询应该是可以的。
但是我不确定这是因为execute()默认情况下不会根据手册抛出异常。我尝试了几个操作,如重复的PK和唯一的约束违规,当我插入的东西。我的断言是受支持的:PDO会抛出异常,我可以从DB获取detaield错误msg。但是我不知道这是否是普遍的真理。是否可以从execute()获取false,当我将ERRMODE设置为最大值时,不会抛出PDOEXCEPTION? *
推荐答案
尝试这样:
try {
//Initial query processing
$execute = $query->execute()
if (!$execute) {
//catch the exception
throw new Exception ("blah")
}
} catch (Exception $e) {
//Exception logic here
}
如果他们在 try
部分遇到异常,它将转发到 catch
部分,然后你可以处理它喜欢(不管id是否取决于某种情况)。
Write your queries like this & if they encounter an exception in the try
section, it will relay to the catch
section and you can handle it however you like (whether or not id depends on a certain case).
如果没有异常,它将永远不会到达 catch
语句,您的查询将只执行。
If there are no exceptions it will never reach the catch
statement, and your query will just execute.
当涉及到 DUPLICATES - >你需要在SQL中解决这个问题。例如,您的查询可以是:
When it comes to DUPLICATES -> you need to work around this in SQL. For example your query could be :
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6) ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);
这篇关于会将false返回的PDO execute()与抛出的异常相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!