亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python帶動態(tài)參數(shù)功能的sqlite工具類

 更新時間:2018年05月26日 13:41:50   作者:A_輝  
這篇文章主要介紹了Python帶動態(tài)參數(shù)功能的sqlite工具類,涉及Python針對sqlite數(shù)據(jù)庫的連接、查詢、sql語句執(zhí)行等相關(guān)操作封裝與使用技巧,需要的朋友可以參考下

本文實(shí)例講述了Python帶動態(tài)參數(shù)功能的sqlite工具類。分享給大家供大家參考,具體如下:

最近在弄sqlite和python

在網(wǎng)上參考各教程后,結(jié)合以往java jdbc數(shù)據(jù)庫工具類寫出以下python連接sqlite的工具類

寫得比較繁瑣 主要是想保留一種類似java的Object…args動態(tài)參數(shù)寫法 并兼容數(shù)組/list方式傳遞不定個數(shù)參數(shù) 并且返回值是List形式 dict字典 以便和JSON格式互相轉(zhuǎn)換

在python中有一些區(qū)別 經(jīng)過該工具類封裝之后可以有以下用法:

db.executeQuery("s * f t w id=? and name=?", "id01", "name01");//動態(tài)參數(shù)形式
db.executeQuery("s * f t w id=? and name=?", ("id01", "name01"));//tuple元組式 等價上面 括號可省略
db.executeQuery("s * f t w id=? and name=?", ["id01", "name01"]);//list數(shù)組形式

完整Python代碼如下:

#!/usr/bin/python
#-*- coding:utf-8 -*-  
import sqlite3
import os 
#
# 連接數(shù)據(jù)庫幫助類
# eg:
#  db = database()
#  count,listRes = db.executeQueryPage("select * from student where id=? and name like ? ", 2, 10, "id01", "%name%")
#  listRes = db.executeQuery("select * from student where id=? and name like ? ", "id01", "%name%")
#  db.execute("delete from student where id=? ", "id01")
#  count = db.getCount("select * from student ")
#  db.close()
#
class database :
  dbfile = "sqlite.db"
  memory = ":memory:"
  conn = None
  showsql = True
  def __init__(self):
    self.conn = self.getConn()
  #輸出工具
  def out(self, outStr, *args):
    if(self.showsql):
      for var in args:
        if(var):
          outStr = outStr + ", " + str(var)
      print("db. " + outStr)
    return 
  #獲取連接
  def getConn(self):
    if(self.conn is None):
      conn = sqlite3.connect(self.dbfile)
      if(conn is None):
        conn = sqlite3.connect(self.memory)
      if(conn is None):
        print("dbfile : " + self.dbfile + " is not found && the memory connect error ! ")
      else:
        conn.row_factory = self.dict_factory #字典解決方案
        self.conn = conn
      self.out("db init conn ok ! ")
    else:
      conn = self.conn
    return conn
  #字典解決方案
  def dict_factory(self, cursor, row): 
    d = {} 
    for idx, col in enumerate(cursor.description): 
      d[col[0]] = row[idx] 
    return d
  #關(guān)閉連接
  def close(self, conn=None):
    res = 2
    if(not conn is None):
      conn.close()
      res = res - 1
    if(not self.conn is None):
      self.conn.close()
      res = res - 1
    self.out("db close res : " + str(res))
    return res
  #加工參數(shù)tuple or list 獲取合理參數(shù)list
  #把動態(tài)參數(shù)集合tuple轉(zhuǎn)為list 并把單獨(dú)的傳遞動態(tài)參數(shù)list從tuple中取出作為參數(shù)
  def turnArray(self, args):
    #args (1, 2, 3) 直接調(diào)用型 exe("select x x", 1, 2, 3)
    #return [1, 2, 3] <- list(args)
    #args ([1, 2, 3], ) list傳入型 exe("select x x",[ 1, 2, 3]) len(args)=1 && type(args[0])=list
    #return [1, 2, 3]
    if(args and len(args) == 1 and (type(args[0]) is list) ):
      res = args[0]
    else:
      res = list(args)
    return res
  #分頁查詢 查詢page頁 每頁num條 返回 分頁前總條數(shù) 和 當(dāng)前頁的數(shù)據(jù)列表 count,listR = db.executeQueryPage("select x x",1,10,(args))
  def executeQueryPage(self, sql, page, num, *args):
    args = self.turnArray(args)
    count = self.getCount(sql, args)
    pageSql = "select * from ( " + sql + " ) limit 5 offset 0 "
    #args.append(num)
    #args.append(int(num) * (int(page) - 1) )
    self.out(pageSql, args) 
    conn = self.getConn()
    cursor = conn.cursor()
    listRes = cursor.execute(sql, args).fetchall()
    return (count, listRes)  
  #查詢列表array[map] eg: [{'id': u'id02', 'birth': u'birth01', 'name': u'name02'}, {'id': u'id03', 'birth': u'birth01', 'name': u'name03'}]
  def executeQuery(self, sql, *args):
    args = self.turnArray(args)
    self.out(sql, args) 
    conn = self.getConn()
    cursor = conn.cursor()
    res = cursor.execute(sql, args).fetchall()
    return res  
  #執(zhí)行sql或者查詢列表 并提交
  def execute(self, sql, *args):
    args = self.turnArray(args)
    self.out(sql, args) 
    conn = self.getConn()
    cursor = conn.cursor()
    #sql占位符 填充args 可以是tuple(1, 2)(動態(tài)參數(shù)數(shù)組) 也可以是list[1, 2] list(tuple) tuple(list)
    res = cursor.execute(sql, args).fetchall()
    conn.commit()
    #self.close(conn)
    return res  
  #查詢列名列表array[str] eg: ['id', 'name', 'birth']
  def getColumnNames(self, sql, *args):
    args = self.turnArray(args)
    self.out(sql, args) 
    conn = self.getConn()
    if(not conn is None):
      cursor = conn.cursor()
      cursor.execute(sql, args)
      res = [tuple[0] for tuple in cursor.description]
    return res  
  #查詢結(jié)果為單str eg: 'xxxx'
  def getString(self, sql, *args):
    args = self.turnArray(args)
    self.out(sql, args) 
    conn = self.getConn()
    cursor = conn.cursor()
    listRes = cursor.execute(sql, args).fetchall()
    columnNames = [tuple[0] for tuple in cursor.description]
    #print(columnNames)
    res = ""
    if(listRes and len(listRes) >= 1):
      res = listRes[0][columnNames[0]]
    return res   
  #查詢記錄數(shù)量 自動附加count(*) eg: 3
  def getCount(self, sql, *args):
    args = self.turnArray(args)
    sql = "select count(*) cc from ( " + sql + " ) "
    resString = self.getString(sql, args)  
    res = 0   
    if(resString):
      res = int(resString)
    return res
####################################測試
def main():
  db = database()
  db.execute(
    ''' 
    create table if not exists student(
      id   text primary key,
      name  text not null,
      birth  text 
    )
    ''' 
  )
  for i in range(10):
    db.execute("insert into student values('id1" + str(i) + "', 'name1" + str(i) + "', 'birth1" + str(i) + "')")
  db.execute("insert into student values('id01', 'name01', 'birth01')")
  db.execute("insert into student values('id02', 'name02', 'birth01')")
  db.execute("insert into student values('id03', 'name03', 'birth01')")
  print(db.getColumnNames("select * from student"))
  print(db.getCount("select * from student " ))
  print(db.getString("select name from student where id = ? ", "id02" ))
  print(db.executeQuery("select * from student where 1=? and 2=? ", 1, 2 ))
  print(db.executeQueryPage("select * from student where id like ? ", 1, 5, "id0%"))
  db.execute("update student set name='nameupdate' where id = ? ", "id02")
  db.execute("delete from student where id = ? or 1=1 ", "id01")
  db.close()
if __name__ == '__main__':
  main()

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python操作SQLite數(shù)據(jù)庫技巧總結(jié)》、《Python常見數(shù)據(jù)庫操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家Python程序設(shè)計有所幫助。

相關(guān)文章

  • 在Python程序中進(jìn)行文件讀取和寫入操作的教程

    在Python程序中進(jìn)行文件讀取和寫入操作的教程

    這篇文章主要介紹了在Python程序中進(jìn)行文件讀取和寫入操作的教程,是Python學(xué)習(xí)當(dāng)中的基礎(chǔ)知識,需要的朋友可以參考下
    2015-04-04
  • python被修飾的函數(shù)消失問題解決(基于wraps函數(shù))

    python被修飾的函數(shù)消失問題解決(基于wraps函數(shù))

    這篇文章主要介紹了python被修飾的函數(shù)消失問題解決(基于wraps函數(shù)),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-11-11
  • PyTorch零基礎(chǔ)入門之構(gòu)建模型基礎(chǔ)

    PyTorch零基礎(chǔ)入門之構(gòu)建模型基礎(chǔ)

    PyTorch是一個開源的Python機(jī)器學(xué)習(xí)庫,基于Torch,用于自然語言處理等應(yīng)用程序,它是一個可續(xù)計算包,提供兩個高級功能:1、具有強(qiáng)大的GPU加速的張量計算(如NumPy)。2、包含自動求導(dǎo)系統(tǒng)的深度神經(jīng)網(wǎng)絡(luò)
    2021-10-10
  • python之super的使用小結(jié)

    python之super的使用小結(jié)

    這篇文章主要介紹了python之super的使用小結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-08-08
  • Pytest allure 命令行參數(shù)的使用

    Pytest allure 命令行參數(shù)的使用

    這篇文章主要介紹了Pytest allure 命令行參數(shù)的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • 利用python繪制蜂群圖的示例代碼

    利用python繪制蜂群圖的示例代碼

    蜂群圖可以不重疊的顯示各數(shù)據(jù)點(diǎn)的分布,相對于散點(diǎn)圖,所繪制的點(diǎn)彼此靠近且不會重疊,能有效呈現(xiàn)出點(diǎn)分布的局部密度信息,本文給大家介紹了如何利用python繪制蜂群圖,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下
    2024-03-03
  • Django中對通過測試的用戶進(jìn)行限制訪問的方法

    Django中對通過測試的用戶進(jìn)行限制訪問的方法

    這篇文章主要介紹了Django中對通過測試的用戶進(jìn)行限制訪問的方法,Django是眾多Python高人氣web框架中最為著名的一個,需要的朋友可以參考下
    2015-07-07
  • Python3爬蟲之urllib攜帶cookie爬取網(wǎng)頁的方法

    Python3爬蟲之urllib攜帶cookie爬取網(wǎng)頁的方法

    今天小編就為大家分享一篇Python3爬蟲之urllib攜帶cookie爬取網(wǎng)頁的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • Python?if?else條件語句形式詳解

    Python?if?else條件語句形式詳解

    這篇文章主要介紹了Python?if?else條件語句形式詳解,在?Python?中,可以使用?if?else?語句對條件進(jìn)行判斷,然后根據(jù)不同的結(jié)果執(zhí)行不同的代碼,這稱為選擇結(jié)構(gòu)或者分支結(jié)構(gòu),接下來小編就根據(jù)情況的不同介紹if?else條件語句形式的不同,需要的朋友可以參考一下
    2022-03-03
  • Python實(shí)現(xiàn)模擬時鐘代碼推薦

    Python實(shí)現(xiàn)模擬時鐘代碼推薦

    本文給大家匯總介紹了下使用Python實(shí)現(xiàn)模擬時鐘的代碼,一共3個例子,后兩個是基于QT實(shí)現(xiàn),有需要的小伙伴可以參考下
    2015-11-11

最新評論