【发布时间】:2011-10-08 00:51:58
【问题描述】:
我以前没有使用过 psycopg2,但我正在尝试将光标工厂更改为 DictCursor,以便 fetchall 或 fetchone 将返回字典而不是列表。
我创建了一个测试脚本来使事情变得简单,并且只测试这个功能。这是我觉得应该可以工作的一点代码
import psycopg2
import psycopg2.extras
conn = psycopg2.connect("dbname=%s user=%s password=%s" % (DATABASE, USERNAME, PASSWORD))
cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
cur.execute("SELECT * from review")
res = cur.fetchall()
print type(res)
print res
res 变量始终是一个列表,而不是我所期望的字典。
我实现的当前解决方法是使用此函数来构建字典并通过它运行 fetchall 返回的每一行。
def build_dict(cursor, row):
x = {}
for key,col in enumerate(cursor.description):
x[col[0]] = row[key]
return d
Python 是 2.6.7 版,psycopg2 是 2.4.2 版。
【问题讨论】:
-
令人惊讶的是,有多少答案忽略了 DictCursor 不起作用的实际问题。如果 DictCursor 问题没有解决,一半的变通方法将无法工作。
标签: python postgresql dictionary psycopg2