溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么用Python實現(xiàn)sqlite3增刪改查的封裝

發(fā)布時間:2021-12-03 15:05:25 來源:億速云 閱讀:364 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“怎么用Python實現(xiàn)sqlite3增刪改查的封裝”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

開發(fā)背景:

每次項目都要寫數(shù)據(jù)庫、煩死了。。然后就每次數(shù)據(jù)庫都要花很多時間。煩死了!不如寫個通用的增刪查改,以不變應(yīng)萬變!

特性:

  • 搭建通用增刪查改模塊,減少代碼量。

  • 讓代碼更加清晰、可讀

  • 即便進行了封裝,也絲毫不影響其靈活性

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ù)設(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)

“怎么用Python實現(xiàn)sqlite3增刪改查的封裝”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI