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)

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog