Home > php教程 > php手册 > PDO 常用类库

PDO 常用类库

WBOY
Release: 2016-06-13 10:46:45
Original
831 people have browsed it

1、Db.class.php

// 连接数据库  
class Db { 
    static public function getDB() { 
        try { 
            $pdo = new PDO(DB_DSN, DB_USER, DB_PWD); 
            $pdo->setAttribute(PDO::ATTR_PERSISTENT, true);  // 设置数据库连接为持久连接  
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  // 设置抛出错误  
            $pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true);  // 设置当字符串为空转换为 SQL 的 NULL  
            $pdo->query('SET NAMES utf8');  // 设置数据库编码  
        } catch (PDOException $e) { 
            exit('数据库连接错误,错误信息:'. $e->getMessage()); 
        } 
        return $pdo; 
    } 

?> 
// 连接数据库
class Db {
 static public function getDB() {
  try {
   $pdo = new PDO(DB_DSN, DB_USER, DB_PWD);
   $pdo->setAttribute(PDO::ATTR_PERSISTENT, true); // 设置数据库连接为持久连接
   $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  // 设置抛出错误
   $pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true);  // 设置当字符串为空转换为 SQL 的 NULL
   $pdo->query('SET NAMES utf8');  // 设置数据库编码
  } catch (PDOException $e) {
   exit('数据库连接错误,错误信息:'. $e->getMessage());
  }
  return $pdo;
 }
}
?>
2、Model.class.php


// 操作 SQL  
class Model { 
    /**
     * SQL 增删改操作,返回受影响的行数
     * @param string $sql
     * @return int
     */ 
    public function aud($sql) { 
        try { 
            $pdo = Db::getDB(); 
            $row = $pdo->exec($sql); 
        } catch (PDOException $e) { 
            exit($e->getMessage()); 
        } 
        return $row; 
    } 
     
    /**
     * 返回全部数据,返回 PDOStatement 对象
     * @param string $sql
     * @return PDOStatement
     */ 
    public function getAll($sql) { 
        try { 
            $pdo = Db::getDB(); 
            $result = $pdo->query($sql); 
            return $result; 
        } catch (PDOException $e) { 
            exit($e->getMessage()); 
        } 
    } 

?> 


摘自 Lee.的专栏
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template