简体   繁体   English

PDO :: exec异常处理中的错误

[英]Error in PDO::exec exception handling

I have an issue with the exception handling of PDO::exec. 我对PDO :: exec的异常处理有问题。 In the following example I have an existing PDO connection and want to execute a sql-statement. 在下面的示例中,我有一个现有的PDO连接,并且想要执行sql语句。 This works quite well so far, but it does not work if I hand over a faulty query. 到目前为止,此方法效果很好,但如果我交出错误的查询,则无法正常工作。 In this case I want it to process the specified exception, but the program stops with a fatal error without the exception block ever executed. 在这种情况下,我希望它处理指定的异常,但是该程序由于发生致命错误而停止,而没有执行异常块。 Here is the erroneous code snippet: 这是错误的代码段:

try{
   $connection->exec( $query );
} catch( PDOException $err ) {
   echo "caught\n";
   echo $err->getMessage();
}

This results in the error Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; 这将导致错误Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;参阅Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; and the program aborts. 程序中止。

I have also tried: 我也尝试过:

if( $connnection->exec( $query ) === false ) {
   echo "Failure\n";
} else {
   echo "Success\n";
}

which was unfortunately equally unsuccessful. 不幸的是,这同样没有成功。 What is the problem here? 这里有什么问题? Are there perhaps any best practice examples (I haven't found any so far)? 也许有任何最佳做法示例(到目前为止,我还没有发现)?

Most likely it's namespace or xdebug to blame for this uncaught exception. 最有可能是该未捕获的异常归咎于名称空间或xdebug。

Are there perhaps any best practice examples 是否有任何最佳做法示例

Sure. 当然。
Do not use exec(). 不要使用exec()。
Do not wrap your queries in try-catch unless you're doing it only once, in a wrapper and going to re-throw it. 不要将您的查询包装在try-catch中,除非您只进行一次包装,然后将其重新抛出。

and the program aborts. 程序中止。

that's exactly what a good program ought to do when encountered with a faulty query. 当遇到错误的查询时,这正是一个好的程序应该做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM