Home >Backend Development >PHP Tutorial >mysql - php的pdo 如果连接失败如何换到其他数据库

mysql - php的pdo 如果连接失败如何换到其他数据库

WBOY
WBOYOriginal
2016-06-06 20:24:021307browse

如果发现数据库A连接失败,如何能连到数据库B啊
如果不用try catch的方式,要怎么做?因为如果失败,new PDO会直接抛出异常,根本走不到下一步,求大神帮忙!!!!!!!!!!!!!

<code><?php $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>
</code>

回复内容:

如果发现数据库A连接失败,如何能连到数据库B啊
如果不用try catch的方式,要怎么做?因为如果失败,new PDO会直接抛出异常,根本走不到下一步,求大神帮忙!!!!!!!!!!!!!

<code><?php $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>
</code>

在catch中连接,把异常存日志

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn