【问题标题】:PDO get sql error code - must be of the type integerPDO 获取 sql 错误代码 - 必须是整数类型
【发布时间】:2019-01-08 05:46:24
【问题描述】:

如何通过 PDO 从 MYSQL 获取错误代码为整数?

try{
    ...
}
catch(PDOException $e){
    throw new Fatal($e->getMessage(), $e->getCode());
}

$e->getCode() 将返回类似HY000

传递给 Fatal::__construct() 的参数 2 必须是整数类型, 给定的字符串...

... Fatal->__construct('SQLSTATE[HY000]...', 'HY000')

【问题讨论】:

  • 1.这就是 PDOExceptions 的样子。没什么可做的。 2. 如果你只是要重新抛出一个功能相同的异常,为什么还要费心去捕捉它? 3. Exception 构造函数中的第三个参数是$previous,您可以在其中传入上一个 Exception 以进行正确的链接。
  • 因为我通过相同的错误类管道所有致命错误

标签: php mysql pdo


【解决方案1】:

看看$e->errorInfo

http://php.net/manual/en/class.pdoexception.php 说:

错误信息

  • 对应于 PDO::errorInfo() 或 PDOStatement::errorInfo()

http://php.net/manual/en/pdostatement.errorinfo.php 记录errorInfo() 返回的字段。

例子:

try {
        $stmt = $pdo->query("Bogus Query");
} catch (PDOException $e) {
        echo "Caught exception!\n";
        var_dump($e->errorInfo);
}

输出:

Caught exception!
array(3) {
  [0]=>
  string(5) "42000"
  [1]=>
  int(1064)
  [2]=>
  string(157) "You have an error in your SQL syntax; check the manual that corresponds to
      your MySQL server version for the right syntax to use near 'Bogus Query' at line 1"
}

可以看到[1]元素是一个整数。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-09-30
  • 2019-08-16
  • 2023-02-03
  • 1970-01-01
  • 1970-01-01
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多