本文主要是介绍python3 sqlite3操作工具类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本工具类对sqlite3的操作进行了封装,对外只提供初始化和execute()方法,使用极其简单,代码如下:
easy_sqlite.py
import sqlite3class EasySqlite:"""sqlite数据库操作工具类database: 数据库文件地址,例如:db/mydb.db"""_connection = Nonedef __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 ddef 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_factoryelse: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'}]
这篇关于python3 sqlite3操作工具类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!