如何在Python的SQLite查询中返回支持字典与点符号访问的对象?
实现支持索引、字典访问和点符号的SQLite行工厂函数
要同时实现索引访问、字典键访问和点符号属性访问三种行数据获取方式,可以通过继承sqlite3.Row并扩展属性访问能力来实现——既保留sqlite3.Row原有的特性,又能支持点符号调用。
自定义行工厂实现
import sqlite3 class CustomRow(sqlite3.Row): def __getattr__(self, name): try: return self[name] except KeyError: raise AttributeError(f"'CustomRow' object has no attribute '{name}'") def custom_row_factory(cursor, row): return CustomRow(cursor.description, row)
使用示例
# 初始化连接并设置自定义行工厂 conn = sqlite3.connect(':memory:') conn.row_factory = custom_row_factory # 创建表并插入测试数据 cur = conn.cursor() cur.execute("CREATE TABLE movie(title, year, score)") cur.execute(""" INSERT INTO movie VALUES ('Monty Python and the Holy Grail', 1975, 1.2), ('And Now for Something Completely Different', 1971, 2.3) """) conn.commit() # 执行查询并验证三种访问方式 results = conn.execute("select * from movie;") for r in results: print(r[0]) # 索引访问:输出电影标题 print(r['year']) # 字典键访问:输出上映年份 print(r.score) # 点符号访问:输出评分
原理说明
CustomRow继承自sqlite3.Row,因此天然支持索引和字典键两种访问方式- 重写
__getattr__方法,当通过点符号访问属性时,内部尝试用属性名作为键从sqlite3.Row中取值;如果键不存在,则抛出标准的AttributeError,保持和常规属性访问一致的错误行为
内容的提问来源于stack exchange,提问作者scrollout
相关产品推荐
相关产品推荐

