Skip to content

Commit

Permalink
用try..catch捕获PDO连接异常
Browse files Browse the repository at this point in the history
  • Loading branch information
yeszao committed Dec 4, 2017
1 parent 27a2219 commit 6df6858
Showing 1 changed file with 29 additions and 24 deletions.
53 changes: 29 additions & 24 deletions fastphp/Db.php
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
<?php

/**
* 数据库操作类,$pdo属性为静态属性,这样在页面执行周期内,
* 只要经过一次赋值,那么第二次再获取还是首次赋值的内容,这
* 里就是PDO对象,这样可以确保运行期间只有一个数据库连接对
* 像,这种是一种简单的单例模式
* Class Db
*/
class Db
{
private static $pdo = null;

public static function pdo()
{
if (self::$pdo !== null) {
return self::$pdo;
}

$dsn = sprintf('mysql:host=%s;dbname=%s', DB_HOST, DB_NAME);
$option = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);

return self::$pdo = new PDO($dsn, DB_USER, DB_PASS, $option);
}
<?php

/**
* 数据库操作类。
* 其$pdo属性为静态属性,所以在页面执行周期内,
* 只要一次赋值,以后的获取还是首次赋值的内容。
* 这里就是PDO对象,这样可以确保运行期间只有一个
* 数据库连接对象,这是一种简单的单例模式
* Class Db
*/
class Db
{
private static $pdo = null;

public static function pdo()
{
if (self::$pdo !== null) {
return self::$pdo;
}

try {
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8', DB_HOST, DB_NAME);
$option = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);

return self::$pdo = new PDO($dsn, DB_USER, DB_PASS, $option);
} catch (PDOException $e) {
exit($e->getMessage());
}
}
}

0 comments on commit 6df6858

Please sign in to comment.