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实现类似ftp传输文件的网络程序示例
Apr 08 Python
python登陆asp网站页面的实现代码
Jan 14 Python
python使用PyGame模块播放声音的方法
May 20 Python
Python实现类似比特币的加密货币区块链的创建与交易实例
Mar 20 Python
详解python异步编程之asyncio(百万并发)
Jul 07 Python
python对于requests的封装方法详解
Jan 03 Python
python交易记录链的实现过程详解
Jul 03 Python
python数据归一化及三种方法详解
Aug 06 Python
python 采用paramiko 远程执行命令及报错解决
Oct 21 Python
Python操作MySQL数据库的示例代码
Jul 13 Python
如何在mac版pycharm选择python版本
Jul 21 Python
Python程序慢的重要原因
Sep 04 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
PHP 数组遍历顺序理解
2009/09/09 PHP
Yii核心组件AssetManager原理分析
2014/12/02 PHP
PHP使用in_array函数检查数组中是否存在某个值
2015/03/25 PHP
thinkphp框架实现路由重定义简化url访问地址的方法分析
2020/04/04 PHP
javaScript Array(数组)相关方法简述
2009/07/25 Javascript
IE6弹出“已终止操作”的解决办法
2010/11/27 Javascript
jQuery ajax 路由和过滤器使用说明
2011/08/02 Javascript
javascript 随机展示头像实现代码
2011/12/06 Javascript
Javascript alert消息换行的方法
2013/08/07 Javascript
JavaScript通过正则表达式实现表单验证电话号码
2014/03/07 Javascript
JavaScript获取table中某一列的值的方法
2014/05/06 Javascript
使用requestAnimationFrame实现js动画性能好
2015/08/06 Javascript
谈谈JavaScript中function多重理解
2015/08/28 Javascript
vue给input file绑定函数获取当前上传的对象完美实现方法
2017/12/15 Javascript
你可能不知道的前端算法之文字避让(inMap)
2018/01/12 Javascript
Vue 中的受控与非受控组件的实现
2018/12/17 Javascript
Vue表单绑定的实例代码(单选按钮,选择框(单选时,多选时,用 v-for 渲染的动态选项)
2019/05/13 Javascript
vue实现路由懒加载的3种方法示例
2020/09/01 Javascript
python执行子进程实现进程间通信的方法
2015/06/02 Python
Python 实现简单的电话本功能
2015/08/09 Python
python实现unicode转中文及转换默认编码的方法
2017/04/29 Python
python文本数据处理学习笔记详解
2019/06/17 Python
python读csv文件时指定行为表头或无表头的方法
2019/06/26 Python
python实现读取excel文件中所有sheet操作示例
2019/08/09 Python
Pytorch抽取网络层的Feature Map(Vgg)实例
2019/08/20 Python
python图片二值化提高识别率代码实例
2019/08/24 Python
Python3 文章标题关键字提取的例子
2019/08/26 Python
使用Python实现 学生学籍管理系统
2019/11/26 Python
Python 实现一行输入多个数字(用空格隔开)
2020/04/29 Python
Python类super()及私有属性原理解析
2020/06/15 Python
Linux如何为某个操作添加别名
2015/02/05 面试题
新闻学专业个人求职信写作
2014/02/04 职场文书
商场中秋节活动方案
2014/02/07 职场文书
考试作弊检讨书范文
2015/01/27 职场文书
员工手册董事长致辞
2015/07/29 职场文书
执行力心得体会范文
2016/01/11 职场文书