python3 sqlite3操作工具类
来源:互联网 发布:马蓉淘宝店 编辑:程序博客网 时间:2024/06/10 17:41
本工具类对sqlite3的操作进行了封装,对外只提供初始化和execute()方法,使用极其简单,代码如下:
easy_sqlite.py
import sqlite3class EasySqlite: """ sqlite数据库操作工具类 database: 数据库文件地址,例如:db/mydb.db """ _connection = None def __init__(self, database): # 连接数据库 self._connection = sqlite3.connect(database) def _dict_factory(self, cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d def execute(self, sql, args=[], result_dict=True, commit=True)->list: """ 执行数据库操作的通用方法 Args: sql: sql语句 args: sql参数 result_dict: 操作结果是否用dict格式返回 commit: 是否提交事务 Returns: list 列表,例如: [{'id': 1, 'name': '张三'}, {'id': 2, 'name': '李四'}] """ if result_dict: self._connection.row_factory = self._dict_factory else: self._connection.row_factory = None # 获取游标 _cursor = self._connection.cursor() # 执行SQL获取结果 _cursor.execute(sql, args) if commit: self._connection.commit() data = _cursor.fetchall() _cursor.close() return dataif __name__ == '__main__': db = EasySqlite('browser.db') # print(db.execute("select name from sqlite_master where type=?", ['table'])) # print(db.execute("pragma table_info([user])")) # print(execute("insert into user(id, name, password) values (?, ?, ?)", [2, "李四", "123456"])) print(db.execute("select id, name userName, password pwd from user")) print(db.execute("select * from user", result_dict=False)) print(db.execute("select * from user"))
执行输出结果:
[{'id': 1, 'userName': '张三', 'pwd': '123456'}, {'id': 2, 'userName': '李四', 'pwd': '123456'}][(1, '张三', '123456'), (2, '李四', '123456')][{'id': 1, 'name': '张三', 'password': '123456'}, {'id': 2, 'name': '李四', 'password': '123456'}]
阅读全文
0 0
- python3 sqlite3操作工具类
- python3与sqlite3
- python3与sqlite3
- sqlite3工具
- sqlite3操作
- sqlite3操作
- sqlite3 操作
- sqlite3操作
- 一个好用的sqlite3工具类
- 使用sqlite3工具
- sqlite3(python3.4 demo in doc)
- python3提示sqlite3模块不存在解决方法
- SQLite3 数据库基本操作
- SQLITE3 常用操作
- sqlite3数据库操作
- SQLite3简单入门操作
- SQLite3的操作命令
- SQLite3 安装、基本操作
- curl命令小记
- ExifInterface图片附加信息
- Microsoft | Windows Server 2012 Radius setup
- Viewpager的自动轮播加+GridView网上获取数据+小圆点
- p55A配置记录
- python3 sqlite3操作工具类
- 对卷积神经网络中1*1 卷积的理解
- typedef和#define的用法与区别
- java的System.getProperty()方法可以获取的值
- java的继承与接口
- AX代码调用打印机
- jQuery-jqprint实现打印功能
- 写给所有程序员_要不要重构
- maven去掉重复依赖的jar包