/**

* MyPDO

*/

class MyPDO

{

protected static $_instance = null;

protected $dbName = '';

protected $dsn;

protected $dbh;

/**

* 构造

*

* @return MyPDO

*/

private function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)

{

try {

$this->dsn = 'mysql:host='.$dbHost.';dbname='.$dbName;

$this->dbh = new PDO($this->dsn, $dbUser, $dbPasswd);

$this->dbh->exec('SET character_set_connection='.$dbCharset.', character_set_results='.$dbCharset.', character_set_client=binary');

} catch (PDOException $e) {

$this->outputError($e->getMessage());

}

}

/**

* 防止克隆

*

*/

private function __clone() {}

/**

* Singleton instance

*

* @return Object

*/

public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)

{

if (self::$_instance === null) {

self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);

}

return self::$_instance;

}

/**

* Query 查询

*

* @param String $strSql SQL语句

* @param String $queryMode 查询方式(All or Row)

* @param Boolean $debug

* @return Array

*/

public function query($strSql, $queryMode = 'All', $debug = false)

{

if ($debug === true) $this->debug($strSql);

$recordset = $this->dbh->query($strSql);

$this->getPDOError();

if ($recordset) {

$recordset->setFetchMode(PDO::FETCH_ASSOC);

if ($queryMode == 'All') {

$result = $recordset->fetchAll();

} elseif ($queryMode == 'Row') {

$result = $recordset->fetch();

}

} else {

$result = null;

}

return $result;

}

/**

* Update 更新

*

* @param String $table 表名

* @param Array $arrayDataValue 字段与值

* @param String $where 条件

* @param Boolean $debug

* @return Int

*/

public function update($table, $arrayDataValue, $where = '', $debug = false)

{

$this->checkFields($table, $arrayDataValue);

if ($where) {

$strSql = '';

foreach ($arrayDataValue as $key => $value) {

$strSql .= ", `$key`='$value'";

}

$strSql = substr($strSql, 1);

$strSql = "UPDATE `$table` SET $strSql WHERE $where";

} else {

$strSql = "REPLACE INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";

}

if ($debug === true) $this->debug($strSql);

$result = $this->dbh->exec($strSql);

$this->getPDOError();

return $result;

}

/**

* Insert 插入

*

* @param String $table 表名

* @param Array $arrayDataValue 字段与值

* @param Boolean $debug

* @return Int

*/

public function insert($table, $arrayDataValue, $debug = false)

{

$this->checkFields($table, $arrayDataValue);

$strSql = "INSERT INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";

if ($debug === true) $this->debug($strSql);

$result = $this->dbh->exec($strSql);

$this->getPDOError();

return $result;

}

/**

* Replace 覆盖方式插入

*

* @param String $table 表名

* @param Array $arrayDataValue 字段与值

* @param Boolean $debug

* @return Int

*/

public function replace($table, $arrayDataValue, $debug = false)

{

$this->checkFields($table, $arrayDataValue);

$strSql = "REPLACE INTO `$table`(`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";

if ($debug === true) $this->debug($strSql);

$result = $this->dbh->exec($strSql);

$this->getPDOError();

return $result;

}

/**

* Delete 删除

*

* @param String $table 表名

* @param String $where 条件

* @param Boolean $debug

* @return Int

*/

public function delete($table, $where = '', $debug = false)

{

if ($where == '') {

$this->outputError("'WHERE' is Null");

} else {

$strSql = "DELETE FROM `$table` WHERE $where";

if ($debug === true) $this->debug($strSql);

$result = $this->dbh->exec($strSql);

$this->getPDOError();

return $result;

}

}

/**

* execSql 执行SQL语句

*

* @param String $strSql

* @param Boolean $debug

* @return Int

*/

public function execSql($strSql, $debug = false)

{

if ($debug === true) $this->debug($strSql);

$result = $this->dbh->exec($strSql);

$this->getPDOError();

return $result;

}

/**

* 获取字段最大值

*

* @param string $table 表名

* @param string $field_name 字段名

* @param string $where 条件

*/

public function getMaxValue($table, $field_name, $where = '', $debug = false)

{

$strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table";

if ($where != '') $strSql .= " WHERE $where";

if ($debug === true) $this->debug($strSql);

$arrTemp = $this->query($strSql, 'Row');

$maxValue = $arrTemp["MAX_VALUE"];

if ($maxValue == "" || $maxValue == null) {

$maxValue = 0;

}

return $maxValue;

}

/**

* 获取指定列的数量

*

* @param string $table

* @param string $field_name

* @param string $where

* @param bool $debug

* @return int

*/

public function getCount($table, $field_name, $where = '', $debug = false)

{

$strSql = "SELECT COUNT($field_name) AS NUM FROM $table";

if ($where != '') $strSql .= " WHERE $where";

if ($debug === true) $this->debug($strSql);

$arrTemp = $this->query($strSql, 'Row');

return $arrTemp['NUM'];

}

/**

* 获取表引擎

*

* @param String $dbName 库名

* @param String $tableName 表名

* @param Boolean $debug

* @return String

*/

public function getTableEngine($dbName, $tableName)

{

$strSql = "SHOW TABLE STATUS FROM $dbName WHERE Name='".$tableName."'";

$arrayTableInfo = $this->query($strSql);

$this->getPDOError();

return $arrayTableInfo[0]['Engine'];

}

/**

* beginTransaction 事务开始

*/

private function beginTransaction()

{

$this->dbh->beginTransaction();

}

/**

* commit 事务提交

*/

private function commit()

{

$this->dbh->commit();

}

/**

* rollback 事务回滚

*/

private function rollback()

{

$this->dbh->rollback();

}

/**

* transaction 通过事务处理多条SQL语句

* 调用前需通过getTableEngine判断表引擎是否支持事务

*

* @param array $arraySql

* @return Boolean

*/

public function execTransaction($arraySql)

{

$retval = 1;

$this->beginTransaction();

foreach ($arraySql as $strSql) {

if ($this->execSql($strSql) == 0) $retval = 0;

}

if ($retval == 0) {

$this->rollback();

return false;

} else {

$this->commit();

return true;

}

}

/**

* checkFields 检查指定字段是否在指定数据表中存在

*

* @param String $table

* @param array $arrayField

*/

private function checkFields($table, $arrayFields)

{

$fields = $this->getFields($table);

foreach ($arrayFields as $key => $value) {

if (!in_array($key, $fields)) {

$this->outputError("Unknown column `$key` in field list.");

}

}

}

/**

* getFields 获取指定数据表中的全部字段名

*

* @param String $table 表名

* @return array

*/

private function getFields($table)

{

$fields = array();

$recordset = $this->dbh->query("SHOW COLUMNS FROM $table");

$this->getPDOError();

$recordset->setFetchMode(PDO::FETCH_ASSOC);

$result = $recordset->fetchAll();

foreach ($result as $rows) {

$fields[] = $rows['Field'];

}

return $fields;

}

/**

* getPDOError 捕获PDO错误信息

*/

private function getPDOError()

{

if ($this->dbh->errorCode() != '00000') {

$arrayError = $this->dbh->errorInfo();

$this->outputError($arrayError[2]);

}

}

/**

* debug

*

* @param mixed $debuginfo

*/

private function debug($debuginfo)

{

var_dump($debuginfo);

exit();

}

/**

* 输出错误信息

*

* @param String $strErrMsg

*/

private function outputError($strErrMsg)

{

throw new Exception('MySQL Error: '.$strErrMsg);

}

/**

* destruct 关闭数据库连接

*/

public function destruct()

{

$this->dbh = null;

}

}

?>

mysql 单例模式好处_PHP单例模式的优点分析相关推荐

  1. php mysql 单例模式_php单例模式

    单例即一个类是能有一个实例,并提供一个当前类的全局唯一访问入口(getInstance).防止类被多次实例化和clone. 一.单例模式<?php class Singleton { priva ...

  2. java单例模式_Java 实现单例模式的 9 种方法

    Linux编程点击右侧关注,免费入门到精通! 作者丨java团长 一. 什么是单例模式 因进程需要,有时我们只需要某个类同时保留一个对象,不希望有更多对象,此时,我们则应考虑单例模式的设计. 二. 单 ...

  3. linux mysql 释放x锁_MySQL 加锁处理分析-转载

    背景 MySQL/InnoDB的加锁分析,一直是一个比较困难的话题.我在工作过程中,经常会有同事咨询这方面的问题.同时,微博上也经常会收到MySQL锁相关的私信,让我帮助解决一些死锁的问题.本文,准备 ...

  4. php对象好用吗,在数据库中使用对象的好处_php

    我们都知道如何从mysql获取我们需要的行(记录),读取数据,然后存取一些改动.很明显也很直接,在这个过程背后也没有什么拐弯抹角的.然而对于我们使用面对对象的程序设计(OOP)来管理我们数据库中的数据 ...

  5. 高亚芳 mysql_MySQL · 专家投稿 · MySQL数据库SYS CPU高的可能性分析

    MySQL · 专家投稿 · MySQL数据库SYS CPU高的可能性分析 问题背景 我们在管理繁忙的 MySQL 数据库时,可能都有碰到 SYS CPU 高的经历:系统突然 SYS CPU 高起来, ...

  6. MYSQL批量插入数据库实现语句性能分析

    MYSQL批量插入数据库实现语句性能分析 假定我们的表结构如下 代码如下   CREATE TABLE example ( example_id INT NOT NULL, name VARCHAR( ...

  7. MySQL 通用查询日志和慢查询日志分析

    MySQL中的日志包括:错误日志.二进制日志.通用查询日志.慢查询日志等等.这里主要介绍下比较常用的两个功能:通用查询日志和慢查询日志. 1)通用查询日志:记录建立的客户端连接和执行的语句. 2)慢查 ...

  8. mysql udf提权_MySQL日志安全分析技巧

    常见的数据库攻击包括弱口令.SQL注入.提升权限.窃取备份等.对数据库日志进行分析,可以发现攻击行为,进一步还原攻击场景及追溯攻击源. 0x01 Mysql日志分析 general query log ...

  9. 【MySQL】MHA部署与MasterFailover代码分析

    [MySQL]MHA部署与MasterFailover代码分析 官网:https://code.google.com/p/mysql-master-ha/ 参考:http://blog.csdn.ne ...

最新文章

  1. 四种常见NLP框架使用总结
  2. 转:http与https
  3. 学python需要记得的单词_学习Python必背的初级单词有哪些?
  4. VTK:PolyData之WarpSurface
  5. 从nginx的编译安装,了解编译安装原理
  6. 为github帐号添加SSH keys
  7. java查看日志命令_[Java教程]【Linux】linux查看日志文件内容命令tail、cat、tac、head、echo...
  8. csplit 分割文件
  9. gprs模块ftp 远程升级_基于GPRS无线通信技术的冷链监测系统
  10. jQuery 基础事件
  11. Linux系统Bash的常用功能(9)
  12. 分析师:苹果或推出自家搜索引擎;曝因芯片缺货,华为智慧屏削减30-40%订单;Rust 1.46.0 发布|极客头条
  13. 金山云肖江:5G+AIoT为智慧社区建设插上翅膀
  14. 原来javaeye变成iteye了
  15. 我的世界服务器修改npc,我的世界npc修改对话框 | 手游网游页游攻略大全
  16. 【mysql 练习题】查询和“01”号同学所学课程完全相同的其他同学的学号
  17. 《python编程:从入门到实践》 练习题 4-11
  18. 统计学第一篇,均值、中位数、众数
  19. 找二叉树根节点到叶子结点最长路径
  20. dependencies 和 devDependencies区别

热门文章

  1. python编程下载安卓版-python编程狮app下载|
  2. 用python画月亮的代码-用 Python 画一个超级月亮
  3. python电脑配置苹果笔记本-tensorflow学习笔记1——mac开发环境配置
  4. python编程基础与应用-Python程序设计基础与应用
  5. 免费学python的软件-初学python编程,有哪些不错的软件值得一用?
  6. Opengl-光照-基本光照-材质(有了材质一个物体才算是完整了)
  7. Revising Aggregations - Averages(集合函数-avg)
  8. C++命名空间 namespace的作用和使用解析
  9. QT官方第三方开源工具
  10. SeekBar的使用(一):实现OnSeekBarChangListener