平時項目中會用到對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;
}
}