您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:利用Python实现sqlite3增删改查的封装

51自学网 2022-02-21 10:46:26
  python
这篇教程利用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='tableselect * from user'select * from user where id = %s'%7select * from user where id = ? , 7select * 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 + cprint(fun1(1, 2, 3))

关键字传递,即通过传递的参数的名称进行识别。

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

默认值参数传递,即给某些参数设置一个默认值,如果不传则读取默认值。

# 默认值传递def fun3(a, b=2, c=3):   return a + b + cprint(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
Python+OpenCV实战之利用
Python&nbsp;OpenCV实战之与机器学习的碰撞

万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。