代码之家  ›  专栏  ›  技术社区  ›  clarkk

PDO get sql错误代码-必须是整数类型

  •  0
  • clarkk  · 技术社区  · 7 年前

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

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

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

    传递给致命::_construct()的参数2必须是整数类型,

    ... 致命->__构造('SQLSTATE[HY000]…','HY000')

    1 回复  |  直到 7 年前
        1
  •  3
  •   Bill Karwin    7 年前

    看看 $e->errorInfo .

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

    错误信息

    • 对应于PDO::errorInfo()或PDO语句::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] 元素是一个整数。

    推荐文章