gpt4 book ai didi

python - psycopg2.extras.DictCursor 不在 postgres 中返回字典

转载 作者:行者123 更新时间:2023-11-29 12:08:08 24 4
gpt4 key购买 nike

我正在使用 psycopg2 通过以下查询访问 postgres 数据库。为了从执行的查询中返回一个字典,我在我的游标中使用了 DictCursor 但我的输出仍然是一个列表而不是字典。

下面是程序和输出。

import psycopg2.extras

try:
conn = psycopg2.connect("user='postgres' host='localhost' password='postgres'",
)
except:
print "I am unable to connect to the database"

cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

cur.execute("""SELECT datname from pg_database""")


rows = cur.fetchall()
print "\nShow me the databases:\n"
print rows

输出:-

[['template1'], ['template0'], ['postgres'], ['iip'], ['test'], ['test_postgres'], ['testdb']]

最佳答案

它看起来像一个列表,闻起来像一个列表,但它是一个 DictRow .

rows = cur.fetchall()
for row in rows :
print(type(row))

#>>> <class 'psycopg2.extras.DictRow'>

这意味着您仍然可以使用列名作为访问数据的键:

rows = cur.fetchall()
print([row['datname'] for row in rows])

This class直接继承自内置的list 并添加实现字典逻辑所需的所有方法,但它不会更改表示形式__repr____str__ , 因此输出与列表相同。

class DictRow(list):
"""A row object that allow by-column-name access to data."""

fetchall() 将所有查询的行打包到一个列表中,而不指定确切的类型。

顺便说一句,也许您正在寻找这种游标:RealDictCursor

关于python - psycopg2.extras.DictCursor 不在 postgres 中返回字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50666600/

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