com*_*mte 8 python postgresql psycopg2 python-3.x
AFAIU和文档,RealDictCursor是一个专门的DictCursor,它只能从密钥(也就是列名)访问列,而DictCursor允许从密钥或索引号访问数据.
我想知道为什么如果DictCursor提供更多的灵活性,RealDictCursor已被实现?它在性能方面(或记忆方面)如此不同(有利于我想象的RealDictCursor)?
换句话说,RealDictCursor用例与DictCursor有什么关系?
kli*_*lin 19
真正的字典游标的主要优点是可以轻松获得 json 格式的查询输出。
相比:
with psycopg2.connect('dbname=test') as connection:
with connection.cursor(cursor_factory=RealDictCursor) as cursor:
cursor.execute("select * from my_table")
print(json.dumps(cursor.fetchall()))
Run Code Online (Sandbox Code Playgroud)
相对
with psycopg2.connect('dbname=test') as connection:
with connection.cursor() as cursor:
cursor.execute("select * from my_table")
columns = [desc[0] for desc in cursor.description]
real_dict = [dict(zip(columns, row)) for row in cursor.fetchall()]
print(json.dumps(real_dict))
Run Code Online (Sandbox Code Playgroud)
在性能方面,这些选项之间没有重要区别。
您无法获得json.dumps(cursor.fetchall())用于常规或类似字典的游标的预期 json ,并且需要上面显示的转换。另一方面,真正的字典游标会产生更大的结果,因此如果您真的不需要它,则不应使用它。