Python带动态参数功能的sqlite工具类


Posted in Python onMay 26, 2018

本文实例讲述了Python带动态参数功能的sqlite工具类。分享给大家供大家参考,具体如下:

最近在弄sqlite和python

在网上参考各教程后,结合以往java jdbc数据库工具类写出以下python连接sqlite的工具类

写得比较繁琐 主要是想保留一种类似java的Object…args动态参数写法 并兼容数组/list方式传递不定个数参数 并且返回值是List形式 dict字典 以便和JSON格式互相转换

在python中有一些区别 经过该工具类封装之后可以有以下用法:

db.executeQuery("s * f t w id=? and name=?", "id01", "name01");//动态参数形式
db.executeQuery("s * f t w id=? and name=?", ("id01", "name01"));//tuple元组式 等价上面 括号可省略
db.executeQuery("s * f t w id=? and name=?", ["id01", "name01"]);//list数组形式

完整Python代码如下:

#!/usr/bin/python
#-*- coding:utf-8 -*-  
import sqlite3
import os 
#
# 连接数据库帮助类
# 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
  #关闭连接
  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
  #加工参数tuple or list 获取合理参数list
  #把动态参数集合tuple转为list 并把单独的传递动态参数list从tuple中取出作为参数
  def turnArray(self, args):
    #args (1, 2, 3) 直接调用型 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条 返回 分页前总条数 和 当前页的数据列表 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  
  #执行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)(动态参数数组) 也可以是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  
  #查询结果为单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   
  #查询记录数量 自动附加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()

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python获取糗百图片代码实例
Dec 18 Python
Python读取一个目录下所有目录和文件的方法
Jul 15 Python
python3中int(整型)的使用教程
Mar 23 Python
python调用Delphi写的Dll代码示例
Dec 05 Python
python实现扫描日志关键字的示例
Apr 28 Python
Python判断对象是否相等及eq函数的讲解
Feb 25 Python
matplotlib实现区域颜色填充
Mar 18 Python
python挖矿算力测试程序详解
Jul 03 Python
Django模型验证器介绍与源码分析
Sep 08 Python
python RSA加密的示例
Dec 09 Python
用Python实现Newton插值法
Apr 17 Python
如何用 Python 子进程关闭 Excel 自动化中的弹窗
May 07 Python
通过Py2exe将自己的python程序打包成.exe/.app的方法
May 26 #Python
python学习笔记--将python源文件打包成exe文件(pyinstaller)
May 26 #Python
Python多重继承的方法解析执行顺序实例分析
May 26 #Python
Python多继承顺序实例分析
May 26 #Python
Python装饰器用法实例总结
May 26 #Python
python 脚本生成随机 字母 + 数字密码功能
May 26 #Python
Python高级用法总结
May 26 #Python
You might like
YII2.0之Activeform表单组件用法实例
2016/01/09 PHP
PHP计算日期相差天数实例分析
2016/02/23 PHP
PHP导出带样式的Excel示例代码
2016/08/28 PHP
php获取客户端IP及URL的方法示例
2017/02/03 PHP
JS隐藏参数post传值实例
2013/04/18 Javascript
window.location的重写及判断location是否被重写
2014/09/04 Javascript
浅谈js中的闭包
2015/03/16 Javascript
Bootstrap开发实战之响应式轮播图
2016/06/02 Javascript
Vue.js每天必学之内部响应式原理探究
2016/09/07 Javascript
Bootstrap源码解读排版(1)
2016/12/23 Javascript
使用node.js对音视频文件加密的实例代码
2017/08/30 Javascript
微信小程序使用wxParse解析html的方法教程
2018/07/06 Javascript
Jquery实现无缝向上循环滚动列表的特效
2019/02/13 jQuery
JavaScript实现刮刮乐效果
2020/11/01 Javascript
微信小程序实现日历小功能
2020/11/18 Javascript
[57:41]Secret vs Serenity 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
[01:06:43]完美世界DOTA2联赛PWL S3 PXG vs GXR 第二场 12.19
2020/12/24 DOTA
python基于queue和threading实现多线程下载实例
2014/10/08 Python
Python编写百度贴吧的简单爬虫
2015/04/02 Python
python使用append合并两个数组的方法
2015/04/28 Python
windows下python连接oracle数据库
2017/06/07 Python
深入浅析Python中的yield关键字
2018/01/24 Python
python3+PyQt5实现自定义分数滑块部件
2018/04/24 Python
python3 requests中使用ip代理池随机生成ip的实例
2018/05/07 Python
Django  ORM 练习题及答案
2019/07/19 Python
python对csv文件追加写入列的方法
2019/08/01 Python
Django之编辑时根据条件跳转回原页面的方法
2019/08/21 Python
Python telnet登陆功能实现代码
2020/04/16 Python
车间班组长的职责
2013/12/13 职场文书
家长评语大全
2014/01/22 职场文书
医疗器械售后服务承诺书
2014/05/21 职场文书
养成教育经验材料
2014/05/26 职场文书
监督检查工作方案
2014/05/28 职场文书
公司庆典欢迎词
2015/01/26 职场文书
导游词之塘栖古镇
2019/12/04 职场文书
java如何实现获取客户端ip地址的示例代码
2022/04/07 Java/Android