平时项目中会用到对SQLite数据库的操作,在此封装一个操作类,方便以后扩展和使用。
class PDOsqlite
{
public $dbcharset = 'utf8';
private $dbFile = '';
public $dbh = null;
protected static $instanceArr = array();
public function __construct($dbname)
{
$this->dbFile = "存放数据库文件的目录" . $dbname;
try {
$this->dbh = new PDO('sqlite:' . $this->dbFile);
} catch (PDOException $e) {
try {
$this->dbh = new PDO('sqlite2:' . $this->dbFile);
} catch (PDOException $e) {
$this->outputError($e->getMessage());
}
}
}
/**
* 单例模式
* @param $dbname
* @return Object
*/
public static function getInstance($dbname)
{
if (!key_exists($dbname, self::$instanceArr)) {
self::$instanceArr[$dbname] = new self($dbname);
}
return self::$instanceArr[$dbname];
}
/**
* @param $tab_name 数据表名
* @param $dataArr 需要插入的字段数组
* @return int|void
*/
public function insert($tab_name, $dataArr)
{
if (is_array($dataArr) && count($dataArr) > 0) {
$key_list = '';
$value_list = '';
foreach ($dataArr as $key => $val) {
$key_list .= "'" . $key . "',";
$value_list .= "'" . $val . "',";
}
$key_list = '(' . rtrim($key_list, ',') . ')';
$value_list = '(' . rtrim($value_list, ',') . ')';
$sql = "insert into $tab_name $key_list values $value_list";
// echo $sql;
$result = $this->dbh->exec($sql);
$this->getPDOError();
//$this->dbh->beginTransaction();//事务回gun
return $result;
}
return;
}
/**
* @param String $tab_name 数据表名
* @param Array $dataArr 需要插入的字段数组
* @param String $type 插入类型,1: 单条,2:批量
* @return int|void
*/
public function replace($tab_name, $dataArr, $type = 1)
{
if (is_array($dataArr) && count($dataArr) > 0) {
$key_list = '';
$value_list = '';
if ($type === 2) {
$keysArr = array();
foreach ($dataArr as $item) {
if (is_array($item) && count($item) > 0) {
$val_list = '';
foreach ($item as $key => $val) {
if (!in_array($key, $keysArr)) {
$keysArr[] = $key;
}
$val_list .= "'" . $val . "',";
}
$val_list = '(' . rtrim($val_list, ',') . '),';
}
$value_list .= $val_list;
}
foreach ($keysArr as $k) {
$key_list .= "'" . $k . "',";
}
$key_list = '(' . rtrim($key_list, ',') . ')';
$value_list = rtrim($value_list, ',');
} else {
foreach ($dataArr as $key => $val) {
$key_list .= "'" . $key . "',";
$value_list .= "'" . $val . "',";
}
$key_list = '(' . rtrim($key_list, ',') . ')';
$value_list = '(' . rtrim($value_list, ',') . ')';
}
$sql = "replace into $tab_name $key_list values $value_list";
// echo $sql;
$result = $this->dbh->exec($sql);
$this->getPDOError();
//$this->dbh->beginTransaction();//事务回gun
return $result;
}
return;
}
/**
* Query 查询
*
* @param String $strSql SQL语句
* @param String $queryMode 查询方式(All or Row)
* @param int $pdoMode 指定数据获取方式
* @param Boolean $debug
* @return Array
*/
public function query($strSql, $queryMode = 'All', $pdoMode = PDO::FETCH_ASSOC, $debug = false)
{
if ($debug === true) $this->debug($strSql);
$recordset = $this->dbh->query($strSql);
$this->getPDOError();
if ($recordset) {
$recordset->setFetchMode($pdoMode);
if ($queryMode == 'All') {
$result = $recordset->fetchAll();
} elseif ($queryMode == 'Row') {
$result = $recordset->fetch();
}
} else {
$result = null;
}
return $result;
}
/**
* Query 查询单条
*
* @param $tab_name 数据表名
* @param $dataArr 查询字段数组
* @param $whereStr 查询条件
* @param Boolean $debug
* @return Array
*/
public function getOne($tab_name, $dataArr = null, $whereStr = null, $debug = false)
{
$inquire_list = '*';
// print_r($dataArr);
if (is_array($dataArr) && count($dataArr) > 0) {
$inquire_list = '';
foreach ($dataArr as $val) {
$inquire_list .= $val . ',';
}
$inquire_list = rtrim($inquire_list, ',');
}
$sql = "SELECT $inquire_list FROM $tab_name $whereStr";
if ($debug === true) $this->debug($sql);
$recordset = $this->dbh->query($sql);
$this->getPDOError();
$result = array();
if ($recordset) {
$recordset->setFetchMode(PDO::FETCH_ASSOC);
$result = $recordset->fetch();
}
return $result;
}
/**
* Query 查询多条
*
* @param $tab_name 数据表名
* @param array $dataArr 查询字段数组
* @param $whereStr 查询条件
* @param Boolean $debug
* @return Array
*/
public function getAll($tab_name, $dataArr = array(), $whereStr = null, $debug = false)
{
$inquire_list = '*';
// print_r($dataArr);
if (is_array($dataArr) && count($dataArr) > 0) {
$inquire_list = '';
foreach ($dataArr as $key => $val) {
$inquire_list .= $val . ',';
}
$inquire_list = rtrim($inquire_list, ',');
}
$sql = "SELECT $inquire_list FROM $tab_name $whereStr";
if ($debug === true) $this->debug($sql);
$recordset = $this->dbh->query($sql);
$this->getPDOError();
$result = array();
if ($recordset) {
$recordset->setFetchMode(PDO::FETCH_ASSOC);
$result = $recordset->fetchAll();
}
return $result;
}
/**
* @param $tab_name 数据表名
* @param $dataArr 需要更新的字段数组
* @param $whereStr 更新条件
* @return int|void
*/
public function update($tab_name, $dataArr, $whereStr)
{
if (is_array($dataArr) && count($dataArr) > 0) {
$field_list = '';
foreach ($dataArr as $key => $val) {
$field_list .= $key . "='{$val}',";
}
$field_list = rtrim($field_list, ',');
$sql = "UPDATE $tab_name SET $field_list $whereStr";
$result = $this->dbh->exec($sql);
$this->getPDOError();
// $this->dbh->beginTransaction();//事务回gun
return $result;
}
return 0;
}
/**
* @param $tab_name 数据表名
* @param $fieldArr 需要删除的字段集合,格式:[key=>[value1, value2,...]]
* @return mixed
*/
public function delete($tab_name, $fieldArr)
{
$res = 0;
if (is_array($fieldArr) && count($fieldArr) > 0) {
$field = key($fieldArr);
if (isset($fieldArr[$field]) && is_array($fieldArr[$field]) && count($fieldArr[$field]) > 0) {
$inquire_list = '';
foreach ($fieldArr[$field] as $val) {
$inquire_list .= "'" . $val . "',";
}
$inquire_list = "(" . rtrim($inquire_list, ',') . ")";
$sql = "DELETE FROM {$tab_name} WHERE {$field} in {$inquire_list}";
$res = $this->dbh->exec($sql);
}
}
return $res;
}
// ===============================================================================
/**创建表
* $tbName 表名
* $sql sql语句
*/
public function createTable($tbName, $sql)
{
if (strlen(trim($tbName)) == 0)
echo "table name is empty!";
if (strlen(trim($sql)) > 0) {
$this->dbh->exec($sql);
$this->getPDOError();
} else {
echo "sql statement is empty!";
}
}
public function sqlQuery($sql, $debug = false)
{
if ($debug === true) $this->debug($sql);
$recordset = $this->dbh->query($sql);
$this->getPDOError();
$result = array();
if ($recordset) {
$recordset->setFetchMode(PDO::FETCH_ASSOC);
$result = $recordset->fetchAll();
}
return $result;
}
public function sqlExec($sql)
{
return $this->dbh->exec($sql);
}
/**
* @param $tab_name 数据表名
* @param string $whereStr 查询条件
* @return mixed
*/
public function total($tab_name, $whereStr = '')
{
$sql = "SELECT COUNT(1) as c FROM {$tab_name} $whereStr";
$rowsCountArr = $this->dbh->query($sql)->fetchAll();
return $rowsCountArr[0]['c'];
}
//获取左后插入的ID
public function lastInsertID()
{
return $this->dbh->lastInsertId();
}
public function clearTab($tab_name)
{
// $res1 = $this->dbh->exec("VACUUM");//清空“空闲列表”,把数据库尺寸压缩到最小。
$res2 = $this->dbh->exec("DELETE FROM $tab_name");
$res3 = $this->dbh->exec("DELETE FROM sqlite_sequence WHERE name = '$tab_name'");
$this->getPDOError();
// return array($res1, $res2, $res3);
return array($res2, $res3);
}
/**
* getPDOError 捕获PDO错误信息
*/
public function getPDOError()
{
if ($this->dbh->errorCode() != '00000') {
$arrayError = $this->dbh->errorInfo();
$this->outputError($arrayError[2]);
}
}
/**
* debug
* @param mixed $debuginfo
*/
public function debug($debuginfo)
{
var_dump($debuginfo);
// exit();
}
/**
* 输出错误信息
*
* @param String $strErrMsg
* @throws Exception
*/
public function outputError($strErrMsg)
{
throw new Exception('MySQL Error: ' . $strErrMsg);
}
/**
* destruct 关闭数据库连接
*/
public function __destruct()
{
$this->dbh = null;
}
}