【发布时间】:2018-04-21 13:54:18
【问题描述】:
我会发现在捕获它时获取导致PDOException 的 sql 语句文本很有用。
据我研究,异常没有该信息。
例如(在阅读了PDOException 类的文档之后),我使用了Exception::__toString() 并得到了类似的东西:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '14' for key 'PRIMARY'
exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '14' for key 'PRIMARY'' in xx.php:64
Stack trace:
#0 xx.php(64): PDOStatement->execute(Array)
#1 xx.php(108): insertKeplerian(Object(MyConn), '14', Object(stdClass))
#2 Command line code(1): include('/srv/www/htdocs...')
#3 {main}
问题是我有从不同函数执行的语句,我想在单个 catch 块中捕获所有异常。
如果确实无法从异常中恢复语句,那么我可以想到两种可能的解决方案:
- 将 sql 语句文本存储在某种“全局”变量中
可以在
catch部分恢复。 - 在每个执行 SQL 语句的函数中捕获和管理
PDOException
我想有更好的方法来做到这一点。
【问题讨论】:
-
恐怕您将不得不构建自己的查询监视器。请参阅this StackOverflow answer 了解更多信息。
-
这并不重要,因为有了堆栈跟踪,您只需单击几下即可导航到问题查询。但无论如何: 3. 创建一个数据库包装器,它会为您运行查询,并在里面有一个 try-catch。