6

我在PHP中收到以下错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'localhost' (10061)' in C:\xampp\htdocs\project\Service\Database.class.php:26 Stack trace: #0 C:\xampp\htdocs\project\Service\Database.class.php(26): PDO->__construct('mysql:host=loca...', 'root', '', Array) #1 C:\xampp\htdocs\project\Service\Database.class.php(54): Service\Database::initialize() #2 C:\xampp\htdocs\project\index.php(15): Service\Database::getHandler() #3 {main} thrown in C:\xampp\htdocs\project\Service\Database.class.php on line 26

错误本身不是问题,我故意终止了Windows 中的MySQL服务以查看发生了什么(我正在使用XAMPP)。问题是我无法捕捉到PDO对象抛出的异常,我不知道为什么。

try {
    $host       = "localhost";
    $dbname     = "project";
    $userName   = "root";
    $password   = "";
    $charset    = "utf8";
    $dsn        = "mysql:host=$host;dbname=$dbname;charset=$charset";

    $driverOptions = array(
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset"
    );

    // This is the line that supposedly throws the exception (LINE 26):
    $dbh = new PDO($dsn, $userName, $password, $driverOptions);

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

    self::setHandler($dbh);
} catch (PDOException $e) {
    die("CATCHED"); // This line is never reached
} catch (Exception $e) {
    die("CATCHED"); // nor this one.
}

我在这里想念什么?

4

2 回答 2

23

我唯一能想到的是,如果您在命名空间类中,并且应该使用\PDOException而不是PDOException.

于 2012-06-05T02:31:36.203 回答
2

打开 error_reporting 并检查错误。

ini_set('display_errors', true);
error_reporting(E_ALL);

在该行之前可能存在致命错误,或者 PDO 不可用。

于 2012-06-05T02:36:22.987 回答