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

相关推荐
前端世界31 分钟前
Linux服务器实战:NTP时间同步、SELinux权限与rsyslog日志管理,一次搞懂三大运维问题
linux·运维·服务器
Android系统攻城狮32 分钟前
Linux Gstreamer深度解析之gst_audio_converter_new调用流程与实战(二十)
linux·运维·服务器·gstreamer音视频·音视频进阶
海宇服务43 分钟前
零信任架构实战:基于海宇对外投资历史查询服务构建自动化供应商准入网关
运维·人工智能·架构·自动化
上海云盾-小余1 小时前
BGP 高防底层原理:TCP 异常流量识别与清洗机制
运维·网络·tcp/ip
captain3761 小时前
▲网络原理(2)-TCP
java·服务器·网络·tcp/ip·java-ee
言乐62 小时前
Python加速器4跨境网络加速器
运维·服务器·开发语言·网络·python
蓝速科技5 小时前
医院导诊 AI 数字人一体机场景适配与落地指南丨蓝速科技
运维·数据库·人工智能·科技·自然语言处理·技术分享
H_oRIZoN_6 小时前
Linux入门DAY41(51 单片机 串口与通信协议)
linux·运维·单片机
小马同学-7 小时前
OpenStack 使用实战:Web 界面与 CLI 命令行实验
运维·云计算·openstack
网安老伯8 小时前
都2026年了,还在问网络安全怎么入门?看完这一篇你就懂了
运维·计算机网络·web安全·网络安全·wireshark·密码学·网络攻击模型