问题
As requested I reformat the question:
For the following code:
$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');
}
Question is, is it possible to see 'A' printed? Will the answer varies for different type of $SQL
like select or insert?
Original question:
- First I set the attribute to PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION, so that, I think, when execute() encounters an error from the DB, it should throw an exception.
Then I realized that if that's true, I may not even have to check the return of execute() as long as an exception thrown is the same as a 'false' returned. I just need to catch from outside. If nothing caught the query should be ok.
But I am not sure about this as execute() does not throw exception according to the manual by default. I tried several operations like duplicate PK and unique constraint violation when I insert something. my assertion is supported: PDO will throw an exception and I can get the detaield error msg from DB. However I don't know whether this is a universal truth. Is it possible to get a false from execute(), and no PDOEXCEPTION thrown when I have set ERRMODE to maximum? *
回答1:
Try this:
try {
//Initial query processing
$execute = $query->execute()
if (!$execute) {
//catch the exception
throw new Exception ("blah")
}
} catch (Exception $e) {
//Exception logic here
}
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).
If there are no exceptions it will never reach the catch
statement, and your query will just execute.
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);
回答2:
I have seen execute() returning false without throwing an exception which is kind of unexpected / bad behaviour in my opinion. This means that we basically have to do both - error and exception handling in parallel.
In my case: if I prepared an insert query without any parameters and then executed with a parameter. Execute will not throw an exception but return false. I suggest anyone to use @mlishn's solution.
来源:https://stackoverflow.com/questions/11617169/will-a-false-returned-pdo-execute-the-same-as-the-exception-it-thrown