封装的 PDO 操作数据库 的帮助类 MySqlHelper

封装的 PDO 操作数据库 的帮助类 MySqlHelper 

封装的 PDO 操作数据库 的帮助类 MySqlHelper ,仅供学习交流使用!

 


/**
 * Description of MySqlHelper
 *
 * @author fx678
 */
 class MySqlHelper {
    private static $pdoDB = null;
    
    public function __destruct() {
        $this->pdoDB = null;
    }
    
    
    /**
     * 获取ini配置文件中PDO连接信息,并返回PDO对象
     * $section: 数据库配置节点
     * 返回 PDO对象
     **/
    private static function getPdoDB($section ="db"){
        if(self::$pdoDB !== null && !array_key_exists($section,array('dsn','username','password'))){
            if(!array_key_exists($section,self::$pdoDB)){
                return self::$pdoDB;
            }
        }   
        
        $config = Config::getConfig($section);
        try {
            self::$pdoDB = new PDO(
                    $config['dsn'], 
                    $config['username'], 
                    $config['password'], 
                    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8';")
            );    
        } catch (Exception $ex) {
            throw new Exception('DB connection error:'.$ex->getMessage());
        }
        
        return self::$pdoDB;
    }
    
    
    /**
     * 执行不带参数的查询语句
     * $connectionString:数据库配置信息节点
     * $strSql:要执行的T-sql 语句
     * 返回 PDOStatement 对象
     **/
    public static function query($connectionString,$strSql){
        try {
           $statement = self::getPdoDB($connectionString)->query($strSql,PDO::FETCH_ASSOC);
           
           if($statement === false){
               throw new Exception($this->getDB($connectionString)->errorInfo());
           }
        } catch (Exception $ex) {
            throw new Execption($ex->getMessage());
        }
        
        return $statement;
     }


     
   /**
     * 执行带参数的查询语句
     * $connectionString:数据库配置信息节点
     * $strSql:要执行的T-sql 语句
     * $paramArr:参数数组
     * 返回 PDOStatement 对象
     **/
    public static function queryParam($connectionString,$strSql,$paramArr){
        try {
            $statement = self::getPdoDB($connectionString)->prepare($strSql);
            
            //获取对应参数
            if(isset($paramArr) && is_array($paramArr)){
                foreach ($paramArr as $key => $val) {
                    $statement->bindParam("$key",$val[0],$val[1]);
                }
            }
            
            //执行
            $statement->execute();    
        } catch (Exception $ex) {
            throw new Execption($ex->getMessage());
        }
        
        if($statement === false){
            throw new Exception($this->getDB($connectionString)->errorInfo());
        }
        
        return $statement;
    }
    
    
    /**
     * 执行带参数并使用事物机制的(增删改)语句
     * $connectionString:数据库配置信息节点
     * $strSql:要执行的T-sql 语句
     * $paramArr:参数数组
     * 返回 返回受影响的行数(int)
     **/
    public static function prepareParamTransaction($connectionString,$strSql,$paramArr){
        $count = 0;
        
        $pdo = self::getPdoDB($connectionString);
        try {
            //关闭自动提交(默认为自动提交)
            $pdo -> setAttribute(PDO::ATTR_AUTOCOMMIT, 0);
            
            //开启异常处理
            $pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
            
            //开始事物
            $pdo -> beginTransaction();
            
            //获取 Statement 对象
            $statement = $pdo->prepare($strSql);
                            
           //获取对应参数
            if(isset($paramArr) && is_array($paramArr)){
                  foreach ($paramArr as $key => $val) {
                      $statement->bindParam("$key",$val[0],$val[1]);
                  }
            }
            
            //执行
            $statement -> execute();
            $count = (int)($statement-> rowCount());
            
            //提交事物
            $pdo -> commit();
        } catch (Exception $ex){
            $pdo ->rollBack();
            throw new Execption($ex->getMessage());
        }
        
        if($statement === false){
            throw new Exception($this->getPdoDB($connectionString)->errorInfo());
        }
        
        //返回受影响的行数
        return $count;
    }
    
    
    /**
     * 执行带参数并使用事物机制的批量处理(增删改)语句
     * $connectionString:数据库配置信息节点
     * $strSql:要执行的T-sql 语句
     * $paramArr:参数数组
     * 返回 返回受影响的行数(int)
     **/
    public static function prepareMoreParamTransaction($connectionString,$strSql,$paramArr){
        $count = 0;
        
        $pdo = self::getPdoDB($connectionString);
        try {
            //关闭自动提交(默认为自动提交)
            $pdo -> setAttribute(PDO::ATTR_AUTOCOMMIT, 0);
            
            //开启异常处理
            $pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
            
            //开始事物
            $pdo -> beginTransaction();
            
            //循环处理
            if(isset($paramArr) && is_array($paramArr)){
               for($i = 0; $i < count($paramArr); $i++){
                  //获取 Statement 对象
                  $statement = $pdo->prepare($strSql);


                  //获取对应参数
                  foreach ($paramArr[$i] as $key => $val) {
                      $statement->bindParam("$key",$val[0],$val[1]);
                  }


                  //执行
                  $statement -> execute();
                  
                  //统计收影响行数
                  $count += (int)($statement-> rowCount());
              }
            }
            
            //提交事物
            $pdo -> commit();
        } catch (Exception $ex){
            $pdo -> rollBack();
            throw new Execption($ex->getMessage());
        }
        
        if($statement === false){
            throw new Exception($this->getPdoDB($connectionString)->errorInfo());
        }
        
        //返回受影响的行数
        return $count;
    }
}

调用参考示例1:

 

 

 $strSql = "SELECT * FROM xxx n WHERE n.`xx`=:xx LIMIT 1;";
        
        $paramArr = array(
            ':Id' => array($Id,  PDO::PARAM_INT)
        );
        
        foreach (self::queryParam(self::$connectionString, $strSql, $paramArr) as $row) {
            $model = new htNewsIndex();
            HtNewsIndexMapper::map($model, $row);
            return $model;
        }
        
        return null;

调用参考示例2:

 

$strSql = "INSERT INTO xxx(xx,xx,xx,xx,xx,xx,xx,xx,xx) "
        . "VALUES(:xx,:xx,:xx,:xx,:xx,:xx,:xx,:xx,:xx);";
        
        //参数数组
        $params = array(
            ':xx'      => array($model->getxx(),PDO::PARAM_STR),
            ':xx'      => array($model->getxx(),PDO::PARAM_STR),
            ':xx'      => array($model->getxx(),PDO::PARAM_STR),
            ':xx'      => array($model->getxx(),PDO::PARAM_STR),
            ':xx'      => array($model->getxx(),PDO::PARAM_STR),
            ':xx'      => array($model->getxx(),PDO::PARAM_STR),
            ':xx'      => array($model->getxx(),PDO::PARAM_STR),
            ':xx'      => array($model->getxx(),PDO::PARAM_STR),
            ':xx'      => array($model->getxx(),PDO::PARAM_INT)
        );
        
        try {
           return (int)self::prepareParamTransaction(self::$connectionString,$strSql,$params);
        } catch (Exception $ex) {
            throw new Exception($ex->getTraceAsString());
        }

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追夢秋陽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值