问题描述
我以前没有使用过psycopg2,但是我试图将光标工厂更改为DictCursor,以便fetchall或fetchone将返回字典而不是列表.
I haven't worked with psycopg2 before but I'm trying to change the cursor factory to DictCursor so that fetchall or fetchone will return a dictionary instead of a list.
我创建了一个测试脚本来简化操作,并且仅测试此功能.这是我觉得应该可以使用的一些代码
I created a test script to make things simple and only test this functionality. Here's my little bit of code that I feel should work
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变量始终是列表,而不是我期望的字典.
The res variable is always a list and not a dictionary as I would expect.
我目前实现的解决方法是使用此功能来构建字典,并通过它运行fetchall返回的每一行.
A current workaround that I've implemented is to use this function that builds a dictionary and run each row returned by fetchall through it.
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.
Python is version 2.6.7 and psycopg2 is version 2.4.2.
推荐答案
res = cur.fetchall()
使res
成为psycopg2.extras.DictRow
s的列表.
或者,您可以利用cur
是可迭代的这一事实来代替调用cur.fetchall
:
Alternatively, instead of calling cur.fetchall
you can take advantage of the fact that cur
is an iterable:
cur.execute("SELECT * from review")
for row in cur:
print(row['column_name'])
,因此您将能够使用类似dict
的语法来访问数据.
and thus you'll be able to access the data with dict
-like syntax.
这篇关于DictCursor在psycopg2下似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!