1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import sqlite3 class 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 data |
近期评论