【问题标题】:PDO exception not catched when accessed using class使用类访问时未捕获 PDO 异常
【发布时间】:2016-04-15 07:37:29
【问题描述】:

我正在使用以下类来创建和访问 PDO 数据库连接:

class DBCxn {
    // What Data Source Name to connect to?
    public static $dsn='mysql:host=localhost;dbname=dbname';
    public static $user = 'root';
    public static $pass = 'root';
    public static $driverOpts = null;

    // Internal variable to hold the connection
    private static $db;
    // no cloning or instantiating allowed
    final private function __construct() {}
    final private function __clone() {}

    public static function get() {
        // Connect if not allready connected
        if (is_null(self::$db)) {
            self::$db = new PDO(self::$dsn, self::$user, self::$pass, self::$driverOpts);       
        }

    // Return the connection
    return self::$db;
    }

}

当我尝试以以下方式访问它并且提供的查询失败(测试而不是测试)时,它不会抛出异常:

$db = DBCxn::get();


try {

    foreach($db->query('SELECT * from tes') as $row) {
        print_r($row);
    }
    $db = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

代码返回警告:为 foreach() 提供的参数无效

为什么没有捕获到异常?

【问题讨论】:

    标签: php oop pdo try-catch


    【解决方案1】:

    PHP 生成的警告和错误(例如您收到的无效参数警告)并非总是例外。即使它们是,您也会专门捕获PDOException,并且无效参数不是PDOException

    PDO::query 如果查询中有错误,通常会返回 false(因此为什么 foreach 会抱怨无效的参数)。要引发异常,您还应该调用

    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    

    在进行查询之前。

    【讨论】:

      猜你喜欢
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多