douzhang1115 2015-05-31 13:10
浏览 91
已采纳

PDO :: setAttribute()似乎不会影响新的PDO()?

I have this code

try {
    $dbh = new PDO('mysql:host=localhost;dbname=db_informations', 'root', '');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo $e->getMessage();
}

And it gives me the exception message:

SQLSTATE[HY000] [1049] Unknown database 'db_informations'

Because the correct name of my database is db_information only.

My question is, even if I don't include the line:

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

I still get the same exception and I think it's not necessary to use it? Is it?

  • 写回答

1条回答 默认 最新

  • dongyan7950 2015-05-31 13:14
    关注

    This is simply because that's the behaviour of PDO::__construct() as you can read in the manual:

    PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails.

    But if you don't set the error mode to Exception and you do:

    try {
        $dbh = new PDO('mysql:host=localhost;dbname=db_informations', 'root', '');
        $dbh->query("SELECT * FROM aTableWhichDoesNotExists");
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
    

    You won't get any excpetion message or error, because you didn't set the error mode. So you need to do this:

    try {
        $dbh = new PDO('mysql:host=localhost;dbname=db_informations', 'root', '');
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $dbh->query("SELECT * FROM aTableWhichDoesNotExists");
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
    

    To receive an exception, which you then can catch:

    SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.atablewhichdoesnotexists' doesn't exist


    Also if you just think logically:

    setAttribute() needs to be used with ->, which means you need an instance of the class to call that method. So how would you be able to call that method, if the instance couldn't be created correctly?

    (So that would mean setAttribute() would have to bee static, so that you can set something/call it before you take the instance of the class)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?