PDO 连接测试 [英] PDO Connection Test

查看:24
本文介绍了PDO 连接测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我有以下代码:

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'
            )));
        }

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

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.

谢谢

推荐答案

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

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:

在 PDO 中使用 MySQL

错误和错误处理

这篇关于PDO 连接测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆