I would like to know how exactly I can deal with the error's statements returned by DataBase Drivers available in PDO class.
我想知道如何准确地处理PDO类中可用的数据库驱动程序返回的错误语句。
As example, let's take the UNIQUE Fields as study-case.
例如,让我们以惟一字段为研究用例。
As you should know, at least when PDO's Debug Mode is active, when trying to add something duplicated in a Database's UNIQUE Field, we receive a PDOException.
您应该知道,至少当PDO的调试模式处于活动状态时,当尝试在数据库的惟一字段中添加重复的内容时,我们会收到一个PDOException。
And I would like to know what is the correct way to handle this. I searched about it and I've got this:
我想知道正确的处理方法是什么。我搜索了一下,发现
try {
// PDO::prepare(), PDOStatement::execute e etc.
} catch( PDOException $e ) {
if( $e -> getCode() == 23000 ) {
// Do something
}
}
But I'm not sure if it's correct and, thinking as programmer, is this really a good practice? I mean, rely on the Error Code?
但是我不确定它是否正确,作为程序员,这真的是一个好的实践吗?我是说,依赖于错误代码?
Even worse: PDO accepts multiple drivers, all they share the same Error Code?
更糟糕的是:PDO接受多个驱动程序,它们共享相同的错误代码吗?
Of course this is not the only case. There are several other Error Codes, right? This "technique" can be used in all the circumstances?
当然,这并不是唯一的情况。还有其他一些错误代码,对吧?这种“技术”在任何情况下都可以使用?
1 个解决方案
#1
3
After looking at http://php.net/manual/en/class.pdoexception.php, I get the feeling that you might need to rely on $e->getMessage()
to find out what the error was.
在查看http://php.net/manual/en/class.pdoexception.php之后,我感觉您可能需要依赖$e->getMessage()来找出错误所在。
Reading through one of the posts provided, you may need to extract the correct error code from the message.
阅读所提供的其中一篇文章,您可能需要从消息中提取正确的错误代码。
PDO seems to have been programmed in a fairly weird way! But it's still pretty invaluable when dealing with multiple database types!
PDO似乎被编程成一种相当奇怪的方式!但是在处理多个数据库类型时,它仍然是非常宝贵的!
#1
3
After looking at http://php.net/manual/en/class.pdoexception.php, I get the feeling that you might need to rely on $e->getMessage()
to find out what the error was.
在查看http://php.net/manual/en/class.pdoexception.php之后,我感觉您可能需要依赖$e->getMessage()来找出错误所在。
Reading through one of the posts provided, you may need to extract the correct error code from the message.
阅读所提供的其中一篇文章,您可能需要从消息中提取正确的错误代码。
PDO seems to have been programmed in a fairly weird way! But it's still pretty invaluable when dealing with multiple database types!
PDO似乎被编程成一种相当奇怪的方式!但是在处理多个数据库类型时,它仍然是非常宝贵的!