php PDO 连接测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6263443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:49:28  来源:igfitidea点击:

PDO Connection Test

phpmysqlpdo

提问by Lee

I am writing an installer for one of my apps and I would like to be able to test some default database settings.

我正在为我的一个应用程序编写一个安装程序,我希望能够测试一些默认的数据库设置。

Is this possible using PDO to test valid and invalid database connections?

这是否可以使用 PDO 来测试有效和无效的数据库连接?

I have the following code:

我有以下代码:

try{
            $dbh = new pdo('mysql:host=127.0.0.1:3308;dbname=axpdb','admin','1234');
            die(json_encode(array('outcome' => true)));
        }catch(PDOException $ex){
            die(json_encode(array(
                'outcome' => false,
                'message' => 'Unable to connect'
            )));
        }

The problem I am having is that the script trys to connect until the script execution time of 60 seconds runs out instead of saying it cannot connect to the db.

我遇到的问题是脚本尝试连接,直到 60 秒的脚本执行时间用完,而不是说它无法连接到数据库。

Thanks

谢谢

回答by Sascha Galley

you need to set the error mode when connection to the database:

连接数据库时需要设置错误模式:

try{
    $dbh = new pdo( 'mysql:host=127.0.0.1:3308;dbname=axpdb',
                    'admin',
                    '1234',
                    array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    die(json_encode(array('outcome' => true)));
}
catch(PDOException $ex){
    die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}

for more infos see the following links:

有关更多信息,请参阅以下链接:

Using MySQL with PDO

将 MySQL 与 PDO 结合使用

Errors and error handling

错误和错误处理

回答by Crozin

As @Sascha Galley already mentioned you should set error mode to exception mode. However, you should also set up PDO::ATTR_TIMEOUTattribute to prevent a long time waiting for response in some cases.

正如@Sascha Galley 已经提到的,您应该将错误模式设置为异常模式。但是,您还应该设置PDO::ATTR_TIMEOUT属性以防止在某些情况下长时间等待响应。

Although documentation says that behavior of this attribute is driver-dependent in case of MySQL it's a connection timeout. You won't find anything about it documentationbut here's a short snippet from driver's source code:

虽然文档说这个属性的行为在 MySQL 的情况下是依赖于驱动程序的,但它是连接超时。你不会找到任何关于它的文档,但这里有一个来自驱动程序源代码的简短片段:

long connect_timeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, 30 TSRMLS_CC);

回答by Sz.

As seen e.g. in the comments at this answer(but hardly anywhere else, so I made it more visible here), the "classic" PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTIONsolution does not always work.

正如在这个答案的评论中看到的(但几乎没有其他任何地方,所以我在这里让它更明显),“经典”PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION解决方案并不总是有效

The implementation of PDO::ERRMODE_EXCEPTIONis broken, so it seems to be "leaking" in some cases.

的实现PDO::ERRMODE_EXCEPTION被破坏,因此在某些情况下似乎是“泄漏”。

For example:

例如:

Warning:PDO::__construct() [pdo.--construct]: [2002] No connection could be made because the target machine actively refused it. (trying to connect via tcp://localhost:3306) in [...]db.phpon line 34

警告:PDO::__construct() [pdo.--construct]: [2002] 无法建立连接,因为目标机器主动拒绝它。(尝试通过 tcp://localhost:3306 连接)在 第34行的[...] db.php

The code there:

那里的代码:

try {
    $this->pdo = new PDO($cfg['DB'], $cfg['DB_USER'], $cfg['DB_PASS'],
        array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch {
    echo("Can't open the database.");
}

The exception isthrown (and cought: I can see my message).

唯一的例外抛出(毫无遗漏和:我可以看到我的消息)。

So, as a necessary workaround, you need to also put a @(let's call it a "diaper operator" in this case)before new pdo(...)to actually keep it clean.

因此,作为必要的解决方法,您还需要实际保持清洁之前放置一个@(在这种情况下我们称之为“尿布操作员”)new pdo(...)

回答by Denis St-Michel

There's a missing closing parenthese at the end of PDO::ERRMODE_EXCEPTION.

PDO::ERRMODE_EXCEPTION 末尾缺少右括号。

Should be:

应该:

$this->pdo = new PDO($cfg['DB'], $cfg['DB_USER'], $cfg['DB_PASS'],
    array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));