pdo使用记录

<?php
/**
 * Created by PhpStorm.
 * User: jin
 * Date: 2015/9/25
 * Time: 11:54
 */
class MysqlDb
{
    static $dbArr = array();
    private $conection = null;
    private $dsn = null;
    private $usernName = null;
    private $userPwd = null;
    private $parameter = null;
    function __construct($username,$pwd,$dbname,$host,$parameter = array())
    {
        $this->dsn='mysql:host='.$host.';dbname='.$dbname;
        $this->usernName = $username;
        $this->userPwd = $pwd;
        $this->parameter = $parameter;
        $this->connect();
    }
    private function connect()
    {
        //当初始化对象失败,也就是连接数据库失败时,会抛出PDOException异常
        try{
            //实例化对象
            $this->conection = new PDO($this->dsn,$this->usernName,$this->userPwd,$this->parameter);
            //设置编码
            $this->conection->exec('set names utf8');
            return true;
        }catch(PDOException $e){
            //结束程序,并打印错误信息
            error_log($e->getMessage(), 0);
            return $e->getMessage();
        }
    }
    //写入操作
    function excute($sql,$parameter = array())
    {
        try
        {
            $prepare = $this->conection->prepare($sql);
            $res = $prepare->execute($parameter);
        }
        catch(PDOException $e)
        {
            if($e->errorInfo[0] == 70100 || $e->errorInfo[0] == 2006){
                $count = 0;
                while(!$this->connect()){
                    sleep(1);
                    echo "数据库重新连接失败(try:{$count})\n";
                    $count++;
                };
                $res = $this->excute($sql, $parameter);
            }
            else
            {
                exit($e->errorInfo[2]);
            }
        }
        return $res;
    }
    //查询操作
    function query($sql,$parameter = array())
    {
        try
        {
            $prepare = $this->conection->prepare($sql);
            $prepare->execute($parameter);
            //设置返回的是索引数组
            $prepare->setFetchMode(PDO::FETCH_ASSOC);
            //取出结果数组
            $row = $prepare->fetchAll();
        }
        catch(PDOException $e)
        {
            if($e->errorInfo[0] == 70100 || $e->errorInfo[0] == 2006){
                $count = 0;
                while(!$this->connect()){
                    sleep(1);
                    echo "数据库重新连接失败(try:{$count})\n";
                    $count++;
                };
                $res = $this->query($sql, $parameter);
            }
            else
            {
                exit($e->errorInfo[2]);
            }
        }
        return $row;
    }
    //只查询第一条
    function find($sql,$parameter = array())
    {
        $row = $this->query($sql,$parameter);
        return current($row);
    }
    //关闭连接
    function close()
    {
        $this->conection = null;
    }
    function getLastInsertId()
    {
        return $this->conection->lastInsertId();
    }
}

标签: none

添加新评论