利用Python實現(xiàn)sqlite3增刪改查的封裝
開發(fā)背景:
每次項目都要寫數(shù)據(jù)庫、煩死了。。然后就每次數(shù)據(jù)庫都要花很多時間。煩死了!不如寫個通用的增刪查改,以不變應萬變!
特性:
- 搭建通用增刪查改模塊,減少代碼量。
- 讓代碼更加清晰、可讀
- 即便進行了封裝,也絲毫不影響其靈活性
sqlite3我也就不多介紹了,直接上代碼。附上相關(guān)使用方法和測試用例!
使用方法
import sqlite3 '''寫一個類打包成庫,通用于儲存信息的sqlite''' '''函數(shù)返回值可優(yōu)化''' '''使用:使用''' '''說明:1、單例模式連接數(shù)據(jù)庫:避免數(shù)據(jù)庫connect過多導致數(shù)據(jù)庫down 2、根據(jù)數(shù)據(jù)庫增刪查改性能對比,統(tǒng)一使用execute進行常規(guī)數(shù)據(jù)庫操作 3、且不做try操作:1、影響性能 2、若報錯,外部調(diào)用無法確定問題所在,''' 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): ''' 關(guān)閉數(shù)據(jù)庫 :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): ''' 執(zhí)行單個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: '''執(zhí)行單條語句:字符串、整型、數(shù)組''' 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
'''對于二次封裝的數(shù)據(jù)庫進行測試'''
'''增刪查改'''
#用例
'''
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參數(shù)傳遞方式
Python的參數(shù)傳遞一共有以下五種(位置參數(shù)、默認參數(shù)、變長參數(shù)、關(guān)鍵字參數(shù)、命名關(guān)鍵字參數(shù))
位置傳遞,即參數(shù)按照定義的位置及順序進行傳遞,如下所示:
# 位置傳遞實例: def fun1(a, b, c): return a + b + c print(fun1(1, 2, 3))
關(guān)鍵字傳遞,即通過傳遞的參數(shù)的名稱進行識別。
# 關(guān)鍵字傳遞 def fun2(a, b, c): return a + b + c print(fun2(1, c=3, b=2))
默認值參數(shù)傳遞,即給某些參數(shù)設置一個默認值,如果不傳則讀取默認值。
# 默認值傳遞 def fun3(a, b=2, c=3): return a + b + c print(fun3(a=1))
元組傳遞,在定義函數(shù)時,我們有時候并不知道調(diào)用的時候會傳遞多少個參數(shù)。元組參數(shù)來進行參數(shù)傳遞會非常有用。如下所示:
def fun4(*name): print(type(name)) print(name) fun4((1, 2, 3))
字典傳遞,雖然通過元組可以傳遞多個參數(shù),但如果需要通過鍵值來獲取參數(shù)內(nèi)容時,字典則更加方便,如下所示:
def fun5(a, b, **kwargs): print(type(kwargs)) # <class 'dict'> print(a, b, kwargs) fun5(2, 3, name='Alan.hsiang', age=23)
總結(jié)
到此這篇關(guān)于利用Python實現(xiàn)sqlite3增刪改查封裝的文章就介紹到這了,更多相關(guān)python?sqlite3增刪改查內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python利用函數(shù)式編程實現(xiàn)優(yōu)化代碼
函數(shù)式編程(Functional Programming)是一種編程范式,它將計算視為函數(shù)的求值,并且避免使用可變狀態(tài)和循環(huán),在Python中還可以利用它的簡潔和高效來解決實際問題,下面我們就來學習一下它的具體用法吧2023-11-11使用python實現(xiàn)回文數(shù)的四種方法小結(jié)
今天小編就為大家分享一篇使用python實現(xiàn)回文數(shù)的四種方法小結(jié),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11