gpt4 book ai didi

python - DictCursor 似乎在 psycopg2 下不起作用

转载 作者:IT老高 更新时间:2023-10-28 20:28:56 24 4
gpt4 key购买 nike

我以前没有使用过 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 版。

最佳答案

使用 RealDictCursor :

import psycopg2.extras

cur = conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor)
cur.execute("SELECT * from review")
res = cur.fetchall()

这为您提供了一个列表,其中包含作为真正的 Python 字典的行,而不是“高级 psycopg2 列表”。

关于python - DictCursor 似乎在 psycopg2 下不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6739355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com