使用 的code
属性PDOException
来获取SQLSTATE
. 请参阅文档PDOException
要控制SQLSTATE
由引发错误的 PL/PgSQL 函数生成,请RAISE ... SQLSTATE
按照文档使用。
当然,为此,数据库驱动程序必须正确报告SQLSTATE
. 我已经验证 PDO 至少在 PHP 5.4.11 和 PostgreSQL 9.2 中执行此操作,根据以下可以使用php
命令行可执行文件执行的独立示例代码:
<?php
$pdo = new PDO('pgsql:');
$sql = <<<EOD
CREATE OR REPLACE FUNCTION exceptiondemo() RETURNS void AS $$
BEGIN
RAISE SQLSTATE 'UE001' USING MESSAGE = 'error message';
END;
$$ LANGUAGE plpgsql
EOD;
$sth = $pdo->prepare($sql);
if (!$sth->execute()) {
die("Failed to create test function\n");
}
$sql = "SELECT exceptiondemo();";
$sth = $pdo->prepare($sql);
if (!$sth->execute()) {
$ei = $sth->errorInfo();
die("Function call failed with SQLSTATE " . $ei[0] . ", message " . $ei[2] . "\n");
// Shortcut way:
// die("Function call failed with SQLSTATE " . $sth->errorCode());
}
?>
输出是:
Function call failed with SQLSTATE UE001, message ERROR: error message
用这个替换从第二个$sth->execute()
到最后的代码块,以证明异常处理模式也可以正常工作:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sth->execute();
} catch (PDOException $err) {
$ei = $err->errorInfo;
die("Function call failed with SQLSTATE " . $ei[0] . ", message " . $ei[2] . "\n");
// Alternate version to just get code:
//die("Function call failed with SQLSTATE " . $err->getCode() . "\n");
}