Python sqlite3 通用增删改查封装与参数传递详解

今天早睡
今天早睡
发布时间:2026-10-15| 4人浏览过
原创

本文介绍如何使用Python封装sqlite3数据库操作,通过单例模式连接数据库并统一使用execute执行常规操作,以简化增删改查流程。文章同时详细解析了Python的五种参数传递方式:位置、关键字、默认值、元组及字典传递,并提供完整代码示例与测试用例,帮助开发者提升代码复用性与灵活性。

开发背景

在多个项目中重复编写数据库操作代码令人感到繁琐且耗时。为了应对这一情况,编写一个通用的增删改查模块成为更优选择,旨在以不变应万变,提高开发效率。

主要特性

  • 构建通用的增删改查模块,有效减少代码冗余量。
  • 使代码结构更加清晰,提升可读性。
  • 尽管进行了封装处理,依然保持操作的灵活性,不受限制。

此处不再赘述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()
 

Python参数传递方式

Python中主要存在五种参数传递机制:位置参数、默认参数、变长参数、关键字参数以及命名关键字参数。

位置传递是指参数严格按照定义时的位置及顺序进行传递,具体示例如下:


# 位置传递实例:
def fun1(a, b, c):
    return a + b + c
print(fun1(1, 2, 3))

关键字传递则是通过指定参数的名称来进行识别和赋值。


# 关键字传递
def fun2(a, b, c):
   return a + b + c
print(fun2(1, c=3, b=2))

默认值参数传递允许为部分参数预设默认值,若调用时未传入该参数,则自动读取默认值。


# 默认值传递
def fun3(a, b=2, c=3):
   return a + b + c
print(fun3(a=1))

元组传递适用于在定义函数时无法确定调用时具体参数数量的场景。通过元组形式传递参数非常实用,示例如下:


def fun4(*name):
    print(type(name))
    print(name)
fun4((1, 2, 3))

字典传递在需要通过键值对获取参数内容时比元组更为便捷,具体示例如下:


def fun5(a, b, **kwargs):
   print(type(kwargs))  # <class 'dict'>
   print(a, b, kwargs)
fun5(2, 3, name='Alan.hsiang', age=23)

总结

至此,关于利用Python实现sqlite3增删改查封装的介绍已完成。如需了解更多相关python sqlite3增删改查内容,建议搜索本站历史文章或继续浏览后续相关文章,感谢支持。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。