数据库操作类mysql/mysqli/pdo

本文涉及的产品
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
RDS AI 助手,专业版
简介:

PDO,MySQL,MYSQLI的各自不同介绍,PDO,MYSQL,MYSQLI 性能哪个比较好

普通的mysql连接肯定是会被抛弃的 因为每次都要防止sql注入的问题 而且相对来说比较慢

首先, mysqli 连接是永久连接,而mysql是非永久连接 。什么意思呢? mysql连接每当第二次使用的时候,都会重新打开一个新的进程,而mysqli则只使用同一个进程,这样可以很大程度的减轻服务器端压力。
mysqli是在普通mysql的基础上做的一次优化说实话很成功 预处理方式完全解决了sql注入的问题 
但是唯一的不足点 就是只支持mysql数据库当然如果你要是不操作其他的数据库或者 当然这无疑是最好的选择 
PDO则是最新出来的一种 连接方式 兼容大部分数据库 也解决了sql注入 但是也有缺点 它只支持php5.1以上的版本不过听说在未来的php6中 只支持这种连接.PDO统一所有数据库抽象层对象接口,mysqli只统一mysql的 

简单说,PDO可以实现同样的代码对不同数据库的操作,例如你从mysql迁移到mssql,程序基本不需要改动 
而mysqli简单理解未mysql的封装就好 在高负载的情况下.PDO开启长连接能够得到一个相对稳定的负载“值”。但是效率却不是最高的。 mysql最快。mysqli其次。只是mysql和mysqli在高并发、系统高负载的时候。其所承担的负载也是很可观的。PDO则不会。http://hudeyong926.iteye.com/blog/1824869

Java代码   收藏代码
  1. <?php  
  2. /** 
  3.  * 数据库操作类 
  4.  */  
  5. class Db  
  6. {  
  7.     protected $db;  
  8.     protected $_sql;  
  9.     protected $throw = 1//抛出sql语句错误信息  
  10.     protected $_query;  
  11.   
  12.     function __construct($dbname = NULL, $port = '3306') {  
  13.         if (!$dbname) {  
  14.             $this->db = new mysqli(HOST, USER, PASS, DBNAME, PORT);  
  15.         } else {  
  16.             $this->db = new mysqli(HOST, USER, PASS, $dbname, $port);  
  17.         }  
  18.   
  19.         $this->db->set_charset(CHARSET);  
  20.   
  21.         if ($this->db->connect_error) {  
  22.             if ($this->throw) {  
  23.                 throw new Exception($this->db->connect_error, $this->db->connect_errno);  
  24.             }  
  25.         }  
  26.   
  27.     }  
  28.   
  29.     /** 
  30.      * 查询字段 
  31.      * @param string $field 要查询的字段 
  32.      * @return Db 
  33.      */  
  34.     public function field($field) {  
  35.         $this->_query['field'] = "SELECT {$field}";  
  36.         return $this;  
  37.     }  
  38.   
  39.     /** 
  40.      * 查询的表名 
  41.      * @param string $table 要查询的表名可以带别名,例如table as tab 
  42.      * @return Db 
  43.      */  
  44.     public function table($table) {  
  45.         $this->_query['table'] = "FROM {$table}";  
  46.         return $this;  
  47.     }  
  48.   
  49.     /** 
  50.      * 联合查询 
  51.      * @param string $join 联合的表名可以带别名,必须加上关联的on语句 
  52.      * @return Db 
  53.      */  
  54.     public function join($join) {  
  55.         $this->_query['join'][] = $join;  
  56.         return $this;  
  57.     }  
  58.   
  59.     /** 
  60.      * 条件语句 
  61.      * @param string $where sql条件语句不需加where关键字 
  62.      * @return Db 
  63.      */  
  64.     public function where($where) {  
  65.         $this->_query['where'] = "WHERE {$where}";  
  66.         return $this;  
  67.     }  
  68.   
  69.     /** 
  70.      * 排序 
  71.      * @param string $order 
  72.      * @return Db 
  73.      */  
  74.     public function order($order) {  
  75.         if ($order != '') {  
  76.             $this->_query['order'] = "ORDER BY {$order}";  
  77.         }  
  78.         return $this;  
  79.     }  
  80.   
  81.     /** 
  82.      * 获取条数 
  83.      * @param string $limit 格式0,5 
  84.      * @return Db 
  85.      */  
  86.     public function limit($limit) {  
  87.         if ($limit != '') {  
  88.             $this->_query['limit'] = "LIMIT {$limit}";  
  89.         }  
  90.         return $this;  
  91.     }  
  92.   
  93.     /** 
  94.      * 构造sql语句 
  95.      * @return string 返回sql语句 
  96.      */  
  97.     private function buildsql() {  
  98.   
  99.         $sql = $this->_query['field'] . ' ' . $this->_query['table'];  
  100.   
  101.         if (!empty($this->_query['join'])) {  
  102.             foreach ($this->_query['join'] as $join) {  
  103.                 $sql .= " {$join}";  
  104.             };  
  105.         }  
  106.   
  107.         if (isset($this->_query['del'])) {  
  108.             $sql = $this->_query['del'] . ' ' . $this->_query['table'];  
  109.         }  
  110.   
  111.         if ($this->_query['where'] != '') {  
  112.             $sql .= ' ' . $this->_query['where'];  
  113.         }  
  114.   
  115.         if (isset($this->_query['order']) && $this->_query['order'] != '') {  
  116.             $sql .= ' ' . $this->_query['order'];  
  117.         }  
  118.         unset($this->_query);  
  119.   
  120.         return $sql;  
  121.   
  122.     }  
  123.   
  124.     /** 
  125.      * 执行select查询 
  126.      * @return bool|array    失败返回FALSE,成功返回二维数组 
  127.      */  
  128.     public function select() {  
  129.         $sql = $this->buildsql();  
  130.   
  131.         return $this->fetchAll($sql);  
  132.     }  
  133.   
  134.     /** 
  135.      * 获取所有记录数 
  136.      * 
  137.      * @return int            返回所有记录数 
  138.      */  
  139.     public function findNumRows() {  
  140.         $sql = $this->buildsql();  
  141.   
  142.         $res = $this->query($sql);  
  143.   
  144.         return $res->num_rows;  
  145.     }  
  146.   
  147.     /** 
  148.      * 删除一行记录 
  149.      * @return boolean 
  150.      */  
  151.     public function delRow() {  
  152.         $this->_query['del'] = "DELETE";  
  153.   
  154.         $sql = $this->buildsql();  
  155.   
  156.         $res = $this->query($sql);  
  157.   
  158.         if ($res === FALSE) {  
  159.             return FALSE;  
  160.         }  
  161.   
  162.         return TRUE;  
  163.     }  
  164.   
  165.     /** 
  166.      * 检查唯一性 
  167.      * 
  168.      * @param string $table 表名 
  169.      * @param string $where 查询条件 
  170.      * @param string $keyid 自动id 
  171.      * @return boolean            存在返回FALSE,否则返回TRUE 
  172.      */  
  173.     public function chkUnique($table, $where, $keyid = 'id') {  
  174.   
  175.         $sql = "SELECT {$keyid} from {$table} WHERE {$where}";  
  176.   
  177.         $num = $this->getNumRows($sql);  
  178.   
  179.         if ($num > 0) {  
  180.             return FALSE;  
  181.         }  
  182.   
  183.         return TRUE;  
  184.     }  
  185.   
  186.     /** 
  187.      * 执行select查询 
  188.      * @return bool|array    失败返回FALSE,成功返回一维数组 
  189.      */  
  190.     public function findRow() {  
  191.         $sql = $this->buildsql();  
  192.   
  193.         return $this->fetchRow($sql);  
  194.     }  
  195.   
  196.     /** 
  197.      * 执行sql语句查询 
  198.      * @param string $sql sql语句 
  199.      * @return mixed 返回资源结果集或布尔值 
  200.      */  
  201.     public function query($sql) {  
  202.         $this->_sql = $sql;  
  203.         $res = $this->db->query($sql);  
  204.   
  205.         if ($res === FALSE) {  
  206.             if ($this->throw) {  
  207.                 throw new Exception("发生错误: 错误信息  {$this->getLastErr()} 相关sql语句 {$this->_sql}", $this->db->errno);  
  208.             } else {  
  209.                 return FALSE;  
  210.             }  
  211.         }  
  212.   
  213.         return $res;  
  214.     }  
  215.   
  216.     /** 
  217.      * 设置是否抛出sql异常 
  218.      * @param bool $bool 
  219.      */  
  220.     public function setThrow($bool = FALSE) {  
  221.         $this->throw = $bool;  
  222.     }  
  223.   
  224.     /** 
  225.      * 执行sql脚本从文件 
  226.      * @param file $sqlfile sql脚本文件路径 
  227.      * @return boolean 
  228.      */  
  229.     public function buildSqlfile($sqlfile) {  
  230.         $file = file($sqlfile);  
  231.   
  232.         if ($file === FALSE || empty($file)) {  
  233.             return FALSE;  
  234.         }  
  235.   
  236.         foreach ($file as $key => $val) {  
  237.             if (preg_match('/^(-|#)/', $val) || trim($val) == '') {  
  238.                 continue;  
  239.             }  
  240.   
  241.             $new[] = $val;  
  242.         }  
  243.   
  244.         $sqls = split(';', join('', $new));  
  245.   
  246.   
  247.         foreach ($sqls as $sql) {  
  248.             $this->query($sql);  
  249.         }  
  250.   
  251.         return TRUE;  
  252.     }  
  253.   
  254.     /** 
  255.      * 获取一条数据 
  256.      * @param string $sql sql语句 
  257.      * @return array 一维数组 
  258.      */  
  259.     public function fetchRow($sql) {  
  260.         $res = $this->query($sql);  
  261.         $result = @$res->fetch_assoc();  
  262.         return $result;  
  263.     }  
  264.   
  265.     /** 
  266.      * 获取多条数据 
  267.      * @param string $sql 
  268.      * @return array 二维数组 
  269.      */  
  270.     public function fetchAll($sql, $key = '') {  
  271.         $res = $this->query($sql);  
  272.   
  273.         $result = array();  
  274.   
  275.         while ($row = $res->fetch_assoc()) {  
  276.             if ($key) {  
  277.                 $result [$row[$key]] = $row;  
  278.             } else {  
  279.                 $result [] = $row;  
  280.             }  
  281.         }  
  282.   
  283.         return $result;  
  284.     }  
  285.   
  286.     /** 
  287.      * 获取所有记录数 
  288.      * 
  289.      * @param string $sql sql语句 
  290.      * @return int            返回所有记录数 
  291.      */  
  292.     public function getNumRows($sql) {  
  293.         $res = $this->query($sql);  
  294.   
  295.         return $res->num_rows;  
  296.     }  
  297.   
  298.     /** 
  299.      * 返回最后查询自动生成的id 
  300.      */  
  301.     public function getLastId() {  
  302.         return $this->db->insert_id;  
  303.     }  
  304.   
  305.     /** 
  306.      * 返回最后查询出现的错误信息 
  307.      */  
  308.     public function getLastErr() {  
  309.         return $this->db->error;  
  310.     }  
  311.   
  312.     /** 
  313.      * 获取最后一次执行的sql语句 
  314.      * 
  315.      * @return string sql 
  316.      */  
  317.     public function getLastSql() {  
  318.         return $this->_sql;  
  319.     }  
  320.   
  321.     /** 
  322.      * 锁定表 
  323.      * @param string $tabname 表名 
  324.      * @param string $mode 模式 
  325.      */  
  326.     public function locktab($tabname, $mode = 'READ') {  
  327.         $this->query("LOCK TABLE {$tabname} {$mode}");  
  328.         return $this;  
  329.     }  
  330.   
  331.     /** 
  332.      * 解锁表 
  333.      */  
  334.     public function unlocktab() {  
  335.         $this->query("UNLOCK TABLES");  
  336.     }  
  337.   
  338.     /** 
  339.      * 执行锁定查询 
  340.      */  
  341.     public function execlockquery() {  
  342.         $sql = $this->buildsql();  
  343.   
  344.     }  
  345.   
  346.     /** 
  347.      * 执行添加记录操作 
  348.      * @param $data        要增加的数据,参数为数组。数组key为字段值,数组值为数据取值 格式:array('字段名' => 值); 
  349.      * @param $table        数据表 
  350.      * @return boolean 
  351.      */  
  352.     public function add($data, $table, $replace = false) {  
  353.         if (!is_array($data) || $table == '' || count($data) == 0) {  
  354.             return false;  
  355.         }  
  356.         $fields = $values = array();  
  357.         //遍历记录, 格式化字段名称与值  
  358.         foreach($data as $key => $val)  
  359.         {  
  360.             $fields[] = "`{$table}`.`{$key}`";  
  361.             $values[] = is_numeric($val) ? $val : "'{$val}'";  
  362.         }  
  363.         $field = join(',', $fields);  
  364.         $value = join(',', $values);  
  365.         unset($fields, $values);  
  366.   
  367.   
  368.         $cmd = $replace ? 'REPLACE INTO' : 'INSERT INTO';  
  369.         $sql = $cmd . ' `' . $table . '`(' . $field . ') VALUES (' . $value . ')';  
  370.         $this->query($sql);  
  371.           
  372.         return $this->getLastId();  
  373.     }  
  374.   
  375.     /** 
  376.      * 执行更新记录操作 
  377.      * @param $table        数据表 
  378.      * @param $data        要更新的数据内容,参数可以为数组也可以为字符串,建议数组。 
  379.      *      为数组时数组key为字段值,数组值为数据取值 
  380.      *      为字符串时[例:`name`='phpcms',`hits`=`hits`+1]。 
  381.      *      为数组时[例: array('name'=>'phpcms','password'=>'123456')] 
  382.      *      数组可使用array('name'=>'+=1', 'base'=>'-=1');程序会自动解析为`name` = `name` + 1, `base` = `base` - 1 
  383.      * 
  384.      * @param $where        更新数据时的条件 
  385.      * @return boolean 
  386.      */  
  387.     public function update($table, $data, $where = '') {  
  388.         if ($table == '' or $where == '') {  
  389.             return false;  
  390.         }  
  391.   
  392.         $where = ' WHERE ' . $where;  
  393.         $field = '';  
  394.         if (is_string($data) && $data != '') {  
  395.             $field = $data;  
  396.         } elseif (is_array($data) && count($data) > 0) {  
  397.             $fields = array();  
  398.             foreach ($data as $k => $v) {  
  399.                 switch (substr($v, 02)) {  
  400.                     case '+=':  
  401.                         $v = substr($v, 2);  
  402.                         if (is_numeric($v)) {  
  403.                             $fields[] =  "`{$k}`=`{$k}` + $v";  
  404.                         } else {  
  405.                             continue;  
  406.                         }  
  407.   
  408.                         break;  
  409.                     case '-=':  
  410.                         $v = substr($v, 2);  
  411.                         if (is_numeric($v)) {  
  412.                             $fields[] =  "`{$k}`=`{$k}` - $v";  
  413.                         } else {  
  414.                             continue;  
  415.                         }  
  416.                         break;  
  417.                     default:  
  418.                         $fields[] =  "`{$k}`= $v";  
  419.                 }  
  420.             }  
  421.             $field = implode(',', $fields);  
  422.         } else {  
  423.             return false;  
  424.         }  
  425.   
  426.         $sql = 'UPDATE `' . $table . '` SET ' . $field . $where;  
  427.         return $this->query($sql);  
  428.     }  
  429.   
  430.     /** 
  431.      * 执行删除记录操作 
  432.      * @param $table        数据表 
  433.      * @param $where        删除数据条件,不充许为空。 
  434.      *                        如果要清空表,使用empty方法 
  435.      * @return boolean 
  436.      */  
  437.     public function delete($table, $where = null) {  
  438.         if ($table == '') {  
  439.             return false;  
  440.         }  
  441.   
  442.         $sql = 'DELETE FROM `' . $table . '`';  
  443.         if ($where) {  
  444.             $sql .= " WHERE {$where}";  
  445.         }  
  446.   
  447.         return $this->query($sql);  
  448.     }  
  449.   
  450.     /** 
  451.      * 自动提交 
  452.      * @param BOOL $status 默认false关闭自动提交,设置为true时打开自动提交 
  453.      */  
  454.     public function autocommit($status = FALSE) {  
  455.         $this->db->autocommit($status);  
  456.     }  
  457.   
  458.     /** 
  459.      * 提交事务 
  460.      */  
  461.     public function commit() {  
  462.         $this->db->commit();  
  463.     }  
  464.   
  465.     /** 
  466.      * 回滚事务 
  467.      */  
  468.     public function rollback() {  
  469.         $this->db->rollback();  
  470.     }  
  471.   
  472.   
  473.     public function __destruct() {  
  474.         $this->db->close();  
  475.     }  
  476.   
  477. }  
 
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
4月前
|
缓存 关系型数据库 BI
使用MYSQL Report分析数据库性能(下)
使用MYSQL Report分析数据库性能
270 60
|
4月前
|
关系型数据库 MySQL 数据库
阿里云数据库RDS费用价格:MySQL、SQL Server、PostgreSQL和MariaDB引擎收费标准
阿里云RDS数据库支持MySQL、SQL Server、PostgreSQL、MariaDB,多种引擎优惠上线!MySQL倚天版88元/年,SQL Server 2核4G仅299元/年,PostgreSQL 227元/年起。高可用、可弹性伸缩,安全稳定。详情见官网活动页。
918 152
|
4月前
|
缓存 监控 关系型数据库
使用MYSQL Report分析数据库性能(中)
使用MYSQL Report分析数据库性能
259 58
|
4月前
|
关系型数据库 MySQL 数据库
阿里云数据库RDS支持MySQL、SQL Server、PostgreSQL和MariaDB引擎
阿里云数据库RDS支持MySQL、SQL Server、PostgreSQL和MariaDB引擎,提供高性价比、稳定安全的云数据库服务,适用于多种行业与业务场景。
|
4月前
|
关系型数据库 MySQL 分布式数据库
阿里云PolarDB云原生数据库收费价格:MySQL和PostgreSQL详细介绍
阿里云PolarDB兼容MySQL、PostgreSQL及Oracle语法,支持集中式与分布式架构。标准版2核4G年费1116元起,企业版最高性能达4核16G,支持HTAP与多级高可用,广泛应用于金融、政务、互联网等领域,TCO成本降低50%。
|
4月前
|
关系型数据库 分布式数据库 数据库
阿里云数据库收费价格:MySQL、PostgreSQL、SQL Server和MariaDB引擎费用整理
阿里云数据库提供多种类型,包括关系型与NoSQL,主流如PolarDB、RDS MySQL/PostgreSQL、Redis等。价格低至21元/月起,支持按需付费与优惠套餐,适用于各类应用场景。
|
4月前
|
SQL 关系型数据库 MySQL
Mysql数据恢复—Mysql数据库delete删除后数据恢复案例
本地服务器,操作系统为windows server。服务器上部署mysql单实例,innodb引擎,独立表空间。未进行数据库备份,未开启binlog。 人为误操作使用Delete命令删除数据时未添加where子句,导致全表数据被删除。删除后未对该表进行任何操作。需要恢复误删除的数据。 在本案例中的mysql数据库未进行备份,也未开启binlog日志,无法直接还原数据库。
|
4月前
|
关系型数据库 MySQL 数据库
自建数据库如何迁移至RDS MySQL实例
数据库迁移是一项复杂且耗时的工程,需考虑数据安全、完整性及业务中断影响。使用阿里云数据传输服务DTS,可快速、平滑完成迁移任务,将应用停机时间降至分钟级。您还可通过全量备份自建数据库并恢复至RDS MySQL实例,实现间接迁移上云。
|
5月前
|
存储 运维 关系型数据库
从MySQL到云数据库,数据库迁移真的有必要吗?
本文探讨了企业在业务增长背景下,是否应从 MySQL 迁移至云数据库的决策问题。分析了 MySQL 的优势与瓶颈,对比了云数据库在存储计算分离、自动化运维、多负载支持等方面的优势,并提出判断迁移必要性的五个关键问题及实施路径,帮助企业理性决策并落地迁移方案。
|
4月前
|
缓存 监控 关系型数据库
使用MYSQL Report分析数据库性能(上)
最终建议:当前系统是完美的读密集型负载模型,优化重点应放在减少行读取量和提高数据定位效率。通过索引优化、分区策略和内存缓存,预期可降低30%的CPU负载,同时保持100%的缓冲池命中率。建议每百万次查询后刷新统计信息以持续优化
346 63

推荐镜像

更多