平时项目中会用到对SQLite数据库的操作,在此封装一个操作类,方便以后扩展和使用。
class PDOsqlite
{
protected static $_instance = null;
public $dbcharset = 'utf8';
public $dbh = null;
public function __construct($dbname)
{
try {
$this->dbh = new PDO('sqlite:' . $dbname);
} catch (PDOException $e) {
try {
$this->dbh = new PDO('sqlite2:' . $dbname);
} catch (PDOException $e) {
exit('error!');
$this->outputError($e->getMessage());
}
}
}
/**
* Singleton instance
* @param $dbname
* @return Object
*/
public static function getInstance($dbname)
{
if (self::$_instance === null) {
self::$_instance = new self($dbname);
}
return self::$_instance;
}
/** 创建数据表
* $tbName 表名
* $sql sql语句
*/
public function createTable($tbName, $sql)
{
if (empty(trim($tbName)))
echo "tabke name is empty!";
if (!empty(trim($sql))) {
// echo $sql;
$ret = $this->dbh->exec($sql);
if (!$ret) {
echo $this->getPDOError();
}
} else {
echo "sql statement is empty!";
}
}
/** 记录查询
* @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;
}
/** 插入纪录
* @param $tab_name 数据表名
* @param $dataArr 需要插入的字段数组
* @param $replace 直接插入还是替换插入,使用replace时,需要指定UNIQUE约束
* @return int|void
*/
public function insert($tab_name, $dataval, $replace = false)
{
if (is_array($dataval) && count($dataval) > 0) {
$key_list = '';
$value_list = '';
foreach ($dataval as $key => $val) {
$key_list .= "'" . $key . "',";
$value_list .= "'" . $val . "',";
}
$key_list = '(' . rtrim($key_list, ',') . ')';
$value_list = '(' . rtrim($value_list, ',') . ')';
$ins = $replace ? 'replace' : 'insert';
$sql = "{$ins} into $tab_name $key_list values $value_list";
// echo $sql;exit();
$result = $this->dbh->exec($sql);
$this->getPDOError();
// $this->dbh->beginTransaction();//事务回gun
return $result;
}
return;
}
/** 更新记录
* @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";
// echo $sql;
$result = $this->dbh->exec($sql);
$this->getPDOError();
// $this->dbh->beginTransaction();//事务回gun
return $result;
}
return;
}
/** 删除记录
* @param $tab_name 数据表名
* @param $fieldArr 需要删除的字段集合
* @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 $key => $val) {
$inquire_list .= "'" . $val . "',";
}
$inquire_list = "(" . rtrim($inquire_list, ',') . ")";
$sql = "DELETE FROM {$tab_name} WHERE {$field} in {$inquire_list}";
// echo $sql;
// exit();
$res = $this->dbh->exec($sql);
}
}
return $res;
}
/** 获取左后插入的ID
* @return number
*/
public function lastInsertID()
{
return $this->dbh->lastInsertId();
}
/** 获取数据表中记录总条数
* @param $tab_name 数据表名
* @param string $whereStr 查询条件
* @return mixed
*/
public function totalCount($tab_name, $whereStr = '')
{
$sql = "SELECT COUNT(1) AS c FROM {$tab_name} $whereStr";
//echo $sql;
$rowsCountArr = $this->dbh->query($sql)->fetch();
// print_r($rowsCountArr);
return $rowsCountArr['c'];
}
/** 清空数据表
* @param $tab_name 数据表名
* @return array
*/
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);
}
/**
* getPDOError 捕获PDO错误信息
*/
public function getPDOError()
{
if ($this->dbh->errorCode() != '00000') {
$arrayError = $this->dbh->errorInfo();
$this->outputError($arrayError[2]);
}
}
/** 返回调试打印信息
* @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;
}
}