服务器运维(十一)SQLite3 php封装——东方仙盟炼气期

代码
defined('THINK_PATH') or exit();
/*** Sqlite数据库驱动* @category Extend* @package Extend* @subpackage Driver.Db* @author liu21st <liu21st@gmail.com>*/
class DbSqlite extends Db {/*** 架构函数 读取数据库配置信息* @access public* @param array $config 数据库配置数组*/public function __construct($config='') {//if ( !extension_loaded('sqlite') ) {if ( !extension_loaded('sqlite3') ) {throw_exception(L('_NOT_SUPPERT_').':sqlite');}if(!empty($config)) {if(!isset($config['mode'])) {$config['mode'] = 0666;}$this->config = $config;if(empty($this->config['params'])) {$this->config['params'] = array();}}}/*** 连接数据库方法* @access public*/public function connect($config='',$linkNum=0) {if ( !isset($this->linkID[$linkNum]) ) {if(empty($config)) $config = $this->config;$pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;$conn = $pconnect ? 'sqlite_popen':'sqlite_open';$this->linkID[$linkNum] = $conn($config['database'],$config['mode']);if ( !$this->linkID[$linkNum]) {throw_exception(sqlite_error_string());}// 标记连接成功$this->connected = true;//注销数据库安全信息if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);}return $this->linkID[$linkNum];}/*** 释放查询结果* @access public*/public function free() {$this->queryID = null;}/*** 执行查询 返回数据集* @access public* @param string $str sql指令* @return mixed*/public function query($str) {$this->initConnect(false);if ( !$this->_linkID ) return false;$this->queryStr = $str;//释放前次的查询结果if ( $this->queryID ) $this->free();N('db_query',1);// 记录开始执行时间G('queryStartTime');$this->queryID = sqlite_query($this->_linkID,$str);$this->debug();if ( false === $this->queryID ) {$this->error();return false;} else {$this->numRows = sqlite_num_rows($this->queryID);return $this->getAll();}}/*** 执行语句* @access public* @param string $str sql指令* @return integer*/public function execute($str) {$this->initConnect(true);if ( !$this->_linkID ) return false;$this->queryStr = $str;//释放前次的查询结果if ( $this->queryID ) $this->free();N('db_write',1);// 记录开始执行时间G('queryStartTime');$result = sqlite_exec($this->_linkID,$str);$this->debug();if ( false === $result ) {$this->error();return false;} else {$this->numRows = sqlite_changes($this->_linkID);$this->lastInsID = sqlite_last_insert_rowid($this->_linkID);return $this->numRows;}}/*** 启动事务* @access public* @return void*/public function startTrans() {$this->initConnect(true);if ( !$this->_linkID ) return false;//数据rollback 支持if ($this->transTimes == 0) {sqlite_query($this->_linkID,'BEGIN TRANSACTION');}$this->transTimes++;return ;}/*** 用于非自动提交状态下面的查询提交* @access public* @return boolen*/public function commit() {if ($this->transTimes > 0) {$result = sqlite_query($this->_linkID,'COMMIT TRANSACTION');if(!$result){$this->error();return false;}$this->transTimes = 0;}return true;}/*** 事务回滚* @access public* @return boolen*/public function rollback() {if ($this->transTimes > 0) {$result = sqlite_query($this->_linkID,'ROLLBACK TRANSACTION');if(!$result){$this->error();return false;}$this->transTimes = 0;}return true;}/*** 获得所有的查询数据* @access private* @return array*/private function getAll() {//返回数据集$result = array();if($this->numRows >0) {for($i=0;$i<$this->numRows ;$i++ ){// 返回数组集$result[$i] = sqlite_fetch_array($this->queryID,SQLITE_ASSOC);}sqlite_seek($this->queryID,0);}return $result;}/*** 取得数据表的字段信息* @access public* @return array*/public function getFields($tableName) {$result = $this->query('PRAGMA table_info( '.$tableName.' )');$info = array();if($result){foreach ($result as $key => $val) {$info[$val['Field']] = array('name' => $val['Field'],'type' => $val['Type'],'notnull' => (bool) ($val['Null'] === ''), // not null is empty, null is yes'default' => $val['Default'],'primary' => (strtolower($val['Key']) == 'pri'),'autoinc' => (strtolower($val['Extra']) == 'auto_increment'),);}}return $info;}/*** 取得数据库的表信息* @access public* @return array*/public function getTables($dbName='') {$result = $this->query("SELECT name FROM sqlite_master WHERE type='table' ". "UNION ALL SELECT name FROM sqlite_temp_master ". "WHERE type='table' ORDER BY name");$info = array();foreach ($result as $key => $val) {$info[$key] = current($val);}return $info;}/*** 关闭数据库* @access public*/public function close() {if ($this->_linkID){sqlite_close($this->_linkID);}$this->_linkID = null;}/*** 数据库错误信息* 并显示当前的SQL语句* @access public* @return string*/public function error() {$code = sqlite_last_error($this->_linkID);$this->error = $code.':'.sqlite_error_string($code);if('' != $this->queryStr){$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;}trace($this->error,'','ERR');return $this->error;}/*** SQL指令安全过滤* @access public* @param string $str SQL指令* @return string*/public function escapeString($str) {return sqlite_escape_string($str);}/*** limit* @access public* @return string*/public function parseLimit($limit) {$limitStr = '';if(!empty($limit)) {$limit = explode(',',$limit);if(count($limit)>1) {$limitStr .= ' LIMIT '.$limit[1].' OFFSET '.$limit[0].' ';}else{$limitStr .= ' LIMIT '.$limit[0].' ';}}return $limitStr;}
}代码总结
- 类定义与构造函数:
DbSqlite类用于管理 SQLite 数据库连接及操作。- 构造函数
__construct检查是否加载了 SQLite3 扩展,若未加载则抛出异常。同时初始化数据库配置,包括设置默认的数据库文件权限mode和确保params参数存在。
- 数据库连接:
connect方法负责建立与 SQLite 数据库的连接。根据配置决定是否使用持久连接,若连接失败则抛出异常,并标记连接状态,注销数据库安全信息。
- 查询与执行操作:
free方法释放查询结果资源。query方法执行 SQL 查询语句,返回数据集。它先初始化连接,执行查询,记录查询次数和时间,处理查询结果并返回所有数据,若查询失败则记录错误。execute方法执行非查询的 SQL 语句(如INSERT、UPDATE、DELETE),返回受影响的行数。同样初始化连接,执行语句,记录操作次数和时间,处理执行结果并记录错误。
- 事务处理:
startTrans方法启动事务,增加事务计数。commit方法提交事务,减少事务计数,若提交失败则记录错误。rollback方法回滚事务,减少事务计数,若回滚失败则记录错误。
- 数据获取:
getAll方法从查询结果中获取所有数据并以数组形式返回。getFields方法获取指定数据表的字段信息,返回一个关联数组,包含字段名、类型、是否可为空、默认值、是否为主键及是否自增等信息。getTables方法获取数据库中的所有表名,返回一个数组。
- 其他操作:
close方法关闭数据库连接。error方法获取并记录数据库错误信息,包括错误代码、错误描述及当前执行的 SQL 语句。escapeString方法对 SQL 指令中的字符串进行安全过滤,防止 SQL 注入。parseLimit方法解析LIMIT参数,生成符合 SQLite 语法的LIMIT子句。
常见场景
- 小型应用程序数据存储:对于资源有限的小型 Web 应用程序或桌面应用程序,SQLite 作为轻量级数据库,无需独立的数据库服务器进程,适合存储用户设置、应用配置等数据。例如,一个简单的个人笔记应用,使用
DbSqlite类可方便地管理笔记数据的存储与查询。 - 快速原型开发:在开发项目原型时,需要快速搭建数据存储与访问功能。使用 SQLite 和
DbSqlite类可以快速实现数据操作,而无需复杂的数据库部署,节省开发时间。例如,开发一个新的电商平台原型,使用该类实现商品、用户等数据的简单管理。 - 嵌入式系统:在一些嵌入式设备中,由于资源受限,无法运行大型数据库系统。SQLite 的轻量级特性使其成为理想选择,
DbSqlite类可帮助开发者方便地在嵌入式设备上进行数据存储和查询操作。比如,智能家居设备中用于存储设备设置和用户操作记录。 - 数据采集与分析:在数据采集应用中,可能需要临时存储采集到的数据,并进行简单的分析。SQLite 可快速存储数据,
DbSqlite类提供的查询功能可满足基本的数据处理需求。例如,气象数据采集站,采集的数据可存储在 SQLite 数据库中,并通过该类进行数据查询和初步分析。
阿雪技术观
让我们积极投身于技术共享的浪潮中,不仅仅是作为受益者,更要成为贡献者。无论是分享自己的代码、撰写技术博客,还是参与开源项目的维护和改进,每一个小小的举动都可能成为推动技术进步的巨大力量
Embrace open source and sharing, witness the miracle of technological progress, and enjoy the happy times of humanity! Let's actively join the wave of technology sharing. Not only as beneficiaries, but also as contributors. Whether sharing our own code, writing technical blogs, or participating in the maintenance and improvement of open source projects, every small action may become a huge force driving technological progrss
