当前位置: 首页 > news >正文

服务器运维(十一)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;}
}

代码总结

  1. 类定义与构造函数
    • DbSqlite类用于管理 SQLite 数据库连接及操作。
    • 构造函数__construct检查是否加载了 SQLite3 扩展,若未加载则抛出异常。同时初始化数据库配置,包括设置默认的数据库文件权限mode和确保params参数存在。
  2. 数据库连接
    • connect方法负责建立与 SQLite 数据库的连接。根据配置决定是否使用持久连接,若连接失败则抛出异常,并标记连接状态,注销数据库安全信息。
  3. 查询与执行操作
    • free方法释放查询结果资源。
    • query方法执行 SQL 查询语句,返回数据集。它先初始化连接,执行查询,记录查询次数和时间,处理查询结果并返回所有数据,若查询失败则记录错误。
    • execute方法执行非查询的 SQL 语句(如INSERTUPDATEDELETE),返回受影响的行数。同样初始化连接,执行语句,记录操作次数和时间,处理执行结果并记录错误。
  4. 事务处理
    • startTrans方法启动事务,增加事务计数。
    • commit方法提交事务,减少事务计数,若提交失败则记录错误。
    • rollback方法回滚事务,减少事务计数,若回滚失败则记录错误。
  5. 数据获取
    • getAll方法从查询结果中获取所有数据并以数组形式返回。
    • getFields方法获取指定数据表的字段信息,返回一个关联数组,包含字段名、类型、是否可为空、默认值、是否为主键及是否自增等信息。
    • getTables方法获取数据库中的所有表名,返回一个数组。
  6. 其他操作
    • close方法关闭数据库连接。
    • error方法获取并记录数据库错误信息,包括错误代码、错误描述及当前执行的 SQL 语句。
    • escapeString方法对 SQL 指令中的字符串进行安全过滤,防止 SQL 注入。
    • parseLimit方法解析LIMIT参数,生成符合 SQLite 语法的LIMIT子句。

常见场景

  1. 小型应用程序数据存储:对于资源有限的小型 Web 应用程序或桌面应用程序,SQLite 作为轻量级数据库,无需独立的数据库服务器进程,适合存储用户设置、应用配置等数据。例如,一个简单的个人笔记应用,使用DbSqlite类可方便地管理笔记数据的存储与查询。
  2. 快速原型开发:在开发项目原型时,需要快速搭建数据存储与访问功能。使用 SQLite 和DbSqlite类可以快速实现数据操作,而无需复杂的数据库部署,节省开发时间。例如,开发一个新的电商平台原型,使用该类实现商品、用户等数据的简单管理。
  3. 嵌入式系统:在一些嵌入式设备中,由于资源受限,无法运行大型数据库系统。SQLite 的轻量级特性使其成为理想选择,DbSqlite类可帮助开发者方便地在嵌入式设备上进行数据存储和查询操作。比如,智能家居设备中用于存储设备设置和用户操作记录。
  4. 数据采集与分析:在数据采集应用中,可能需要临时存储采集到的数据,并进行简单的分析。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

http://www.dtcms.com/a/588974.html

相关文章:

  • 【C++】多态(1):多态定义实现及虚函数的重写
  • Ascend C 算子开发模式全解析:从 Kernel 到工程化
  • 在 Unity 游戏开发中,为视频选择 VP8 还是 H.264
  • 【Java知识】OkHttp一款优秀的http客户端工具
  • 建设好网站为什么读取不到文件网站建设官网多少钱
  • 一个FPGA通加载不同程序实现4K edp和V-by-One
  • 脑科学图像处理软件
  • 【C语言实战(79)】深入C语言单元测试:基于CUnit框架的实战指南
  • 会小二也是做会议网站的小地方做外卖网站怎样
  • python+playwright自动化如何解决文件上传问题
  • Linux介绍及常用命令
  • PyTorch中张量和模型的核心属性解析
  • 哈尔滨网站设计公司公司名字大全免费版
  • 大模型知识编辑技术——李宏毅2025《机器学习》第十讲
  • JAVA中next和nextLine的区别
  • 东莞设计网站企业淘宝客建站需要多少钱
  • ROS2 Humble 笔记(十二)launch 文件与 namespace 启动多个节点
  • nginx源码安装以及平滑升级
  • [特殊字符] Spring AOP 注解方式详解
  • C++——二叉搜索树
  • 青少年机器人技术等级考试理论综合试卷(一级)2020年9月
  • Redis_9_Set
  • 计算机网络培训课程大庆网站建设优化
  • 网站正在建设中永久wordpress 前台文章
  • Electron 桌面应用开发入门指南:从零开始打造 Hello World
  • 深入解析手机快充技术原理与实现
  • JavaScript 数组方法大全
  • 电子商务网站建设与管理的实验报告个人怎样免费建网站
  • STM32F103学习笔记-16-RCC(第3节)-使用HSE配置系统时钟并使用MCO输出监控系统时钟
  • LeRobot 入门教程(十五)从Hub加载环境