0

跟进这里的帖子,看来我已经设法扩展了 pdo 类,

class database_extended extends PDO
{

    #make a connection
    public function __construct($dsn,$username,$password)
    {
        try 
        { 
            parent::__construct($dsn,$username,$password);
            //$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch (PDOException $e) 
        {
            # call the get_error function
            self::get_error($e);
        }
    }

    #get the number of rows in a result
    public function num_rows($query)
    {
        try 
        {
            # create a prepared statement
            $stmt = parent::prepare($query);

            # execute query 
            $stmt->execute();

            # return the result
            return $stmt->rowCount();
        } 
        catch (PDOException $e) 
        {
            # call the get_error function
            self::get_error($e);
        }
    }

    # display error
    public function get_error($e) 
    {
        $this->connection = null;
        die($e->getMessage());
    }

    # closes the database connection when object is destroyed.
    public function __destruct()
    {

    }
}

但是好像不太对——我是num_rows故意在查询中有错误的方法测试的,所以这个方法可以返回错误信息,

# the host used to access DB
define('DB_HOST', 'localhost');

# the username used to access DB
define('DB_USER', 'root');

# the password for the username
define('DB_PASS', 'xx');

# the name of your databse 
define('DB_NAME', 'xx_2011');

# the data source name
define('DSN', 'mysql:dbname='.DB_NAME.';host='.DB_HOST);

include 'class_database.php';

$connection = new database_extended(DSN,DB_USER,DB_PASS);

$sql = "
    SELECT *
    FROM table_not_exist
    ORDER BY cnt_id DESC
    ";

echo $connection->num_rows($sql);

它应该返回,

SQLSTATE [42S02]:未找到基表或视图:1146 表 'xx_2011.table_not_exist' 不存在

但它返回了一个0!为什么??我该如何解决?

谢谢。

4

2 回答 2

2

因为PDOStatement::execute没有throw,它只false在失败时返回。因此,您的代码永远不会进入catch块。应该更符合以下原则:

$stmt = parent::prepare($query);

if (!$stmt->execute()) {
    self::get_error();
}

return $stmt->rowCount();
于 2011-03-03T02:44:32.377 回答
0

PDOStatement::execute当查询导致错误时返回 false,它不会抛出异常。如果您想对错误进行处理,您可能应该编写一些代码来检查该返回值。

于 2011-03-03T02:44:21.870 回答