SCTMES_V5/mes_in_sct/libs/db/DbConnection.php

346 lines
8.0 KiB
PHP
Raw Normal View History

2025-06-14 18:55:09 +08:00
<?php
namespace libs\db;
use PDO;
use PDOException;
class DbConnection
{
/**
* 数据库配置信息
* @var array
*/
protected $settings;
/**
* pdo实例
* @var
*/
protected $pdo;
/**
* sql的参数
* @var array
*/
protected $parameters = array();
/**
* 预处理语句
* @var array
*/
protected $sQuery;
/**
* 构造函数
*/
public function __construct($config, $charset = 'utf8')
{
$this->settings = array(
'driver' => $config['driver'],
'host' => $config['host'],
'port' => $config['port'],
'user' => $config['user'],
'password' => $config['password'],
'dbname' => $config['dbname'],
'charset' => $config['charset'] ?? $charset
);
$this->connect();
}
/**
* 创建pdo实例
*/
public function connect()
{
$dsn = sprintf(
"%s:dbname=%s;host=%s;port=%s",
$this->settings["driver"],
$this->settings["dbname"],
$this->settings["host"],
$this->settings["port"]
);
$options = [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . (!empty($this->settings['charset']) ? $this->settings['charset'] : 'utf8')
];
$this->pdo = new PDO($dsn, $this->settings["user"], $this->settings["password"], $options);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
/**
* 获取一行数据
* @param string $query
* @param int $fetchmode
* @return null
*/
public function fetch($query = '', $fetchmode = PDO::FETCH_ASSOC)
{
if (strpos(strtolower($query), "limit") == false) {
$query = rtrim($query, ";") . " limit 1;";
}
$this->execute($query);
$result = $this->sQuery->fetchAll($fetchmode);
if (!empty($result)) {
return $result[0];
}
return null;
}
/**
* 获取多行数据
* @param string $query
* @param int $fetchmode
* @return null
*/
public function fetchAll($query = '', $fetchmode = PDO::FETCH_ASSOC)
{
$this->execute($query);
$result = $this->sQuery->fetchAll($fetchmode);
if (!empty($result)) {
return $result;
}
return null;
}
/**
* 新增
* @param $table
* @param array $params
* @param int $fetchmode
* @return string|null
*/
public function insert($table, $data = [], $fetchmode = PDO::FETCH_ASSOC)
{
if (count($data) == 0) {
return null;
}
$key_str = '';
$val_str = '';
foreach ($data as $key => $val) {
$key_str .= "\"$key\",";
if(is_string($val)){
$val_str .= "'{$val}',";
}else{
$val_str .= "{$val},";
}
}
$key_str = rtrim($key_str, ",");
$val_str = rtrim($val_str, ",");
$query = "INSERT INTO {$table} ({$key_str}) VALUES ({$val_str})";
$this->execute($query);
if ($this->sQuery->rowCount() > 0) {
return $this->lastInsertId();
}
return null;
}
/**
* 修改
* @param $table
* @param array $params
* @return null
*/
public function update($table, $data = [], $params = [])
{
if (count($data) == 0) {
return null;
}
if (count($params) == 0) {
return null;
}
$str = '';
foreach ($data as $key => $val) {
$str .= "\"" . $key . "\"='$val',";
}
$str = rtrim($str, ",");
$query = "UPDATE \"{$table}\" SET {$str} ";
$query .= " WHERE ";
$count = 0;
foreach ($params as $k => $v) {
$count++;
if ($count === count($params)) {
$query .= "\"$k\"='$v' ";
} else {
$query .= "\"$k\"='$v' AND ";
}
}
$this->execute($query);
return $this->sQuery->rowCount();
}
/**
* 删除
* @param $table
* @param array $params
* @return null
*/
public function delete($table, $params = [])
{
if (count($params) == 0) {
return null;
}
$str = '';
$count = 0;
foreach ($params as $k => $v) {
$count++;
if ($count === count($params)) {
$str .= "\"$k\"='$v' ";
} else {
$str .= "\"$k\"='$v' AND ";
}
}
$query = "DELETE FROM \"{$table}\" WHERE {$str}";
$this->execute($query);
return $this->sQuery->rowCount();
}
/**
* 执行SQL
* @param string $query
* @param array $params
* @param int $fetchmode
* @return mixed
*/
public function query($query = '', $params = null, $fetchmode = PDO::FETCH_ASSOC)
{
$this->execute($query, $params);
$rawStatement = explode(" ", $query);
$statement = strtolower(trim($rawStatement[0]));
if ($statement === 'select' || $statement === 'show') {
$result = $this->sQuery->fetchAll($fetchmode);
if (strpos(strtolower($query), 'limit') !== false) {
return $result[0];
} else {
return $result;
}
} elseif ($statement === 'update' || $statement === 'delete') {
return $this->sQuery->rowCount();
} elseif ($statement === 'insert') {
if ($this->sQuery->rowCount() > 0) {
return $this->lastInsertId();
}
} else {
return NULL;
}
}
/**
* 执行
* @param string $query
* @param string $parameters
*/
protected function execute($query, $parameters = "")
{
try {
$this->sQuery = $this->pdo->prepare($query);
if (is_array($parameters)) {
foreach ($parameters as $key => $param) {
$this->sQuery->bindParam($key + 1, $param);
}
}
$this->sQuery->execute();
} catch (PDOException $e) {
$errorCode = $e->getCode();
// 写入错误sql信息
record_sql_log($e->getMessage(),$query);
// 服务端断开时重连一次
if ($errorCode == 'HY000' || $errorCode == '57P01' || $errorCode == '08006' || $errorCode == '08003') {
$this->closeConnection();
$this->connect();
try {
$this->sQuery = $this->pdo->prepare($query);
if (is_array($parameters)) {
foreach ($parameters as $key => $param) {
$this->sQuery->bindParam($key + 1, $param);
}
}
$this->sQuery->execute();
} catch (PDOException $ex) {
$this->rollBackTrans();
throw $ex;
}
} else {
$this->rollBackTrans();
throw $e;
}
}
$this->parameters = array();
}
/**
* 关闭连接
*/
public function closeConnection()
{
$this->pdo = null;
}
/**
* 返回lastInsertId
* @return string
*/
public function lastInsertId()
{
return $this->pdo->lastInsertId();
}
/**
* 开始事务
*/
public function beginTrans()
{
$this->pdo->beginTransaction();
}
/**
* 提交事务
*/
public function commitTrans()
{
$this->pdo->commit();
}
/**
* 事务回滚
*/
public function rollBackTrans()
{
if ($this->pdo->inTransaction()) {
$this->pdo->rollBack();
}
}
}