You need to enable JavaScript to run this app. Python使用databases模块查询sqlite时如何获取字典格式返回结果
优惠活动
大模型
产品
解决方案
定价
更多

Python使用databases模块查询sqlite时如何获取字典格式返回结果

异步databases模块查询结果转字典方案

databases是封装多异步驱动的上层数据库操作库,不适用sqlite3的row_factory配置方案,可通过以下两种方式实现字典格式返回:

方法1:使用内置mapping参数(推荐,适用v0.5.0及以上版本)

fetch_one()、fetch_all()方法原生支持mapping参数,传入True即可直接返回列名对应值的字典格式,无需额外处理:

import databases

# 替换为对应数据库的异步连接串即可,支持PostgreSQL/MySQL/SQLite等
database = databases.Database("mysql+asyncmy://user:password@localhost/dbname")

# 单条查询示例
async def query_single_user(user_id: int):
    await database.connect()
    query = "SELECT id, username, mobile FROM users WHERE id = :uid"
    # 传入mapping=True直接返回字典
    user = await database.fetch_one(query, values={"uid": user_id}, mapping=True)
    await database.disconnect()
    return user

# 批量查询示例
async def query_all_users():
    await database.connect()
    query = "SELECT id, username, mobile FROM users"
    # 返回字典列表,每个元素都是列名对应值的字典
    user_list = await database.fetch_all(query, mapping=True)
    await database.disconnect()
    return user_list

方法2:手动转换Row对象(适用旧版本)

如果使用的是低于0.5.0的版本,无mapping参数支持,可直接通过dict()内置函数转换返回的Row对象:

async def query_single_user_old(user_id: int):
    await database.connect()
    query = "SELECT id, username, mobile FROM users WHERE id = :uid"
    row = await database.fetch_one(query, values={"uid": user_id})
    # 手动转字典,注意先判空避免None转换报错
    user = dict(row) if row else None
    await database.disconnect()
    return user

注意:查询无匹配结果时fetch_one()会返回None,转换前需做判空处理避免抛出异常。

内容的提问来源于stack exchange,提问作者tedzz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 06:36:04