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

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


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


  传递给Fatal :: __ construct()的参数2必须为整数类型,
  给定的字符串...
  
  ...致命-> __ construct('SQLSTATE [HY000] ...','HY000')

最佳答案

看一下$e->errorInfo

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


  errorInfo
  
  
  对应于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]元素是一个整数。

关于php - PDO获取SQL错误代码-必须为整数类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54081759/

10-10 15:01