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)

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

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备