问题描述
AFAIU 和文档中的 RealDictCursor 是一个专门的 DictCursor,它只能从键(又名列名)访问列,而 DictCursor 可以从键或索引号访问数据.
我想知道如果 DictCursor 提供了更大的灵活性,为什么要实现 RealDictCursor?它在性能方面(或内存方面)是否如此不同(我认为有利于 RealDictCursor ......)?
换句话说,什么是 RealDictCursor 用例与 DictCursor?
AFAIU and from docs, RealDictCursor is a specialized DictCursor that enables to access columns only from keys (aka columns name), whereas DictCursor enables to access data both from keys or index number.
I was wondering why RealDictCursor has been implemented if DictCursor offers more flexibility? Is it performance-wise (or memory-wise) so different (in favor of RealDictCursor I imagine...)?
In other words, what are RealDictCursor use cases vs DictCursor?
推荐答案
真正的字典游标的主要优点是可以很容易地获得 json 格式的查询输出.
The main advantage of real dictionary cursor is the easiness to get a query output as 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()))
对比
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))
就性能而言,这些选项之间没有重要区别.
There is no important difference between these options when it comes to performance.
对于常规或类似字典的游标,您无法使用 json.dumps(cursor.fetchall())
获得预期的 json,并且需要进行上述转换.另一方面,真正的字典游标会产生更大的结果,所以如果你真的不需要它,你不应该使用它.
You cannot get an expected json using json.dumps(cursor.fetchall())
for regular or dictionary-like cursors and need the conversion showed above. On the other hand, real dictionary cursor produces a much larger result so you should not use it if you really do not need it.
这篇关于psycopg2:DictCursor 与 RealDictCursor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!