psycopg2:DictCursor 与 RealDictCursor
psycopg2: DictCursor vs RealDictCursor
AFAIU 和来自文档的 RealDictCursor 是一种专用的 DictCursor,它允许仅从键(又名列名)访问列,而 DictCursor 允许从键或索引号访问数据。
我想知道如果 DictCursor 提供更多灵活性,为什么要实施 RealDictCursor?它在性能方面(或内存方面)是否如此不同(我想有利于 RealDictCursor ...)?
换句话说,什么是 RealDictCursor 用例与 DictCursor?
class psycopg2.extras.RealDictCursor(*args, **kwargs)
使用真正的字典作为行的基本类型的游标。请注意,此游标非常专业,不允许正常访问(使用整数索引)获取数据。如果您需要同时以字典和列表的形式访问数据库行,请使用通用的 DictCursor 而不是 RealDictCursor。 class psycopg2.extras.RealDictConnection 自动使用 RealDictCursor 的连接。
注意
自 Psycopg2.5 以来不是很有用:您可以使用 psycopg2.connect(dsn, cursor_factory=RealDictCursor) 而不是 RealDictConnection . class
psycopg2.extras.RealDictRow(cursor) 表示a的dict subclass
数据记录.
真正的字典游标的主要优点是很容易获得查询输出 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))
就性能而言,这些选项之间没有重要区别。
对于常规或类似字典的游标,使用 json.dumps(cursor.fetchall())
无法获得预期的 json,需要进行上述转换。另一方面,真正的字典游标会产生更大的结果,所以如果你真的不需要它,你不应该使用它。
AFAIU 和来自文档的 RealDictCursor 是一种专用的 DictCursor,它允许仅从键(又名列名)访问列,而 DictCursor 允许从键或索引号访问数据。
我想知道如果 DictCursor 提供更多灵活性,为什么要实施 RealDictCursor?它在性能方面(或内存方面)是否如此不同(我想有利于 RealDictCursor ...)?
换句话说,什么是 RealDictCursor 用例与 DictCursor?
class psycopg2.extras.RealDictCursor(*args, **kwargs)
使用真正的字典作为行的基本类型的游标。请注意,此游标非常专业,不允许正常访问(使用整数索引)获取数据。如果您需要同时以字典和列表的形式访问数据库行,请使用通用的 DictCursor 而不是 RealDictCursor。 class psycopg2.extras.RealDictConnection 自动使用 RealDictCursor 的连接。
注意 自 Psycopg2.5 以来不是很有用:您可以使用 psycopg2.connect(dsn, cursor_factory=RealDictCursor) 而不是 RealDictConnection . class psycopg2.extras.RealDictRow(cursor) 表示a的dict subclass 数据记录.
真正的字典游标的主要优点是很容易获得查询输出 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))
就性能而言,这些选项之间没有重要区别。
对于常规或类似字典的游标,使用 json.dumps(cursor.fetchall())
无法获得预期的 json,需要进行上述转换。另一方面,真正的字典游标会产生更大的结果,所以如果你真的不需要它,你不应该使用它。