Python实现sqlite3增删改查的封装

简介: Python实现sqlite3增删改查的封装

Python实现sqlite3增删改查的封装,可直接调用接口


前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。


特性:


  • 搭建通用增删查改模块,减少代码量。
  • 让代码更加清晰、可读
  • 即便进行了封装,也丝毫不影响其灵活性


sqlite3我也就不多介绍了,直接上代码。附上相关使用方法和测试用例!

import sqlite3
'''写一个类打包成库,通用于储存信息的sqlite'''
'''函数返回值可优化'''
'''使用:使用'''
'''说明:1、单例模式连接数据库:避免数据库connect过多导致数据库down
        2、根据数据库增删查改性能对比,统一使用execute进行常规数据库操作
        3、且不做try操作:1、影响性能 2、若报错,外部调用无法确定问题所在,'''
class LiteDb(object):
    _instance = None
    def __new__(cls, *args, **kw):
        if cls._instance is None:
            cls._instance = object.__new__(cls)
        return cls._instance
    def openDb(self, dbname):
        self.dbname = dbname
        self.conn = sqlite3.connect(self.dbname)
        self.cursor = self.conn.cursor()
    def closeDb(self):
        '''
        关闭数据库
        :return:
        '''
        self.cursor.close()
        self.conn.close()
    def createTables(self, sql):
        '''
        example:'create table userinfo(name text, email text)'
        :return: result=[1,None]  
        '''
        self.cursor.execute(sql)
        self.conn.commit()
        result = [1, None]
        return result
    def dropTables(self, sql):
        '''
        example:'drop table userinfo'
        :param sql:
        :return:result=[1,None]
        '''
        self.cursor.execute(sql)
        self.conn.commit()
        result = [1, None]
        return result
    def executeSql(self, sql, value=None):
        '''
        执行单个sql语句,只需要传入sql语句和值便可
        :param sql:'insert into user(name,password,number,status) values(?,?,?,?)'
                    'delete from user where name=?'
                    'updata user set status=? where name=?'
                    'select * from user where id=%s'
        :param value:[(123456,123456,123456,123456),(123,123,123,123)]
                value:'123456'
                value:(123,123)
        :return:result=[1,None]
        '''
        '''增、删、查、改'''
        if isinstance(value,list) and isinstance(value[0],(list,tuple)):
            for valu in value:
                self.cursor.execute(sql, valu)
            else:
                self.conn.commit()
                result = [1, self.cursor.fetchall()]
        else:
            '''执行单条语句:字符串、整型、数组'''
            if value:
                self.cursor.execute(sql, value)
            else:
                self.cursor.execute(sql)
            self.conn.commit()
            result = [1, self.cursor.fetchall()]
        return result


测试用例

from dbUse import LiteDb
'''对于二次封装的数据库进行测试'''
'''增删查改'''
#用例
'''
select name from sqlite_master where type='table
select * from user
'select * from user where id = %s'%7
select * from user where id = ? , 7
select * from user where id=? or id=?, ['7','8']
insert  into user(id) values(7)
'insert  into user(id) values(%s)'%7
'insert  into user(id) values(?)',[('10',),('11',)]
delete from user where id=7
'delete from user where id=%s'%7
'delete from user where id=?',[('10',),('11',)]
update user set id=7 where id=11
'update user set id=%s where id=%s'%(10,20)
'update user set id=? where id=?',[('21','11'),('20','10')]'''
db=LiteDb()
db.openDb('user.db')
def close():
    db.closeDb()
def createTables():
    result=db.createTables('create table if not exists user(id varchar(128))')
def executeSQL():
    '''增删查改'''
    result = db.executeSql('insert  into user(id) values(?)',('99',))
    result = db.executeSql('select * from user ')
executeSQL()
close()
相关文章
|
3月前
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
358 0
|
4月前
|
人工智能 自然语言处理 安全
Python构建MCP服务器:从工具封装到AI集成的全流程实践
MCP协议为AI提供标准化工具调用接口,助力模型高效操作现实世界。
928 1
|
7月前
|
SQL 数据库 开发者
Python中使用Flask-SQLAlchemy对数据库的增删改查简明示例
这样我们就对Flask-SQLAlchemy进行了一次简明扼要的旅程,阐述了如何定义模型,如何创建表,以及如何进行基本的数据库操作。希望你在阅读后能对Flask-SQLAlchemy有更深入的理解,这将为你在Python世界中从事数据库相关工作提供极大的便利。
714 77
|
Python
用python转移小文件到指定目录并压缩,脚本封装
这篇文章介绍了如何使用Python脚本将大量小文件转移到指定目录,并在达到大约250MB时进行压缩。
172 2
|
关系型数据库 MySQL 数据库
Python处理数据库:MySQL与SQLite详解 | python小知识
本文详细介绍了如何使用Python操作MySQL和SQLite数据库,包括安装必要的库、连接数据库、执行增删改查等基本操作,适合初学者快速上手。
1161 15
|
弹性计算 数据管理 数据库
从零开始构建员工管理系统:Python与SQLite3的完美结合
本文介绍如何使用Python和Tkinter构建一个图形界面的员工管理系统(EMS)。系统包括数据库设计、核心功能实现和图形用户界面创建。主要功能有查询、添加、删除员工信息及统计员工数量。通过本文,你将学会如何结合SQLite数据库进行数据管理,并使用Tkinter创建友好的用户界面。
564 2
从零开始构建员工管理系统:Python与SQLite3的完美结合
|
Web App开发 SQL 数据库
使用 Python 解析火狐浏览器的 SQLite3 数据库
本文介绍如何使用 Python 解析火狐浏览器的 SQLite3 数据库,包括书签、历史记录和下载记录等。通过安装 Python 和 SQLite3,定位火狐数据库文件路径,编写 Python 脚本连接数据库并执行 SQL 查询,最终输出最近访问的网站历史记录。
324 4
|
关系型数据库 MySQL 数据库
Mysql学习笔记(四):Python与Mysql交互--实现增删改查
如何使用Python与MySQL数据库进行交互,实现增删改查等基本操作的教程。
207 1
|
存储 关系型数据库 数据库
轻量级数据库的利器:Python 及其内置 SQLite 简介
轻量级数据库的利器:Python 及其内置 SQLite 简介
457 3
|
关系型数据库 MySQL Python
mysql之python客户端封装类
mysql之python客户端封装类

推荐镜像

更多