【问题标题】:What is the right way of getting rows from PostgreSQL database using Psycopg2?使用 Psycopg2 从 PostgreSQL 数据库获取行的正确方法是什么?
【发布时间】:2021-03-21 23:18:13
【问题描述】:

我正在尝试在 python 烧瓶应用程序中获取 PostgreSQL 数据库连接,我想让它返回行,这样我就可以对列进行基于名称的访问。我尝试按照 Psycopg2 文档进行操作,但没有成功。

代码如下:

def get_connection():        
    conn = psycopg2.connect(dbname=DB_USER, user=DB_USER, password=DB_PASS, host=DB_HOST)
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictRow)
    return cur

根据documentation 似乎很好,但我收到了一个错误:

File "/app/app.py", line 34, in get_connection
cur = conn.cursor(cursor_factory=psycopg2.extras.DictRow)
TypeError: __init__() takes 2 positional arguments but 3 were given

有人可以帮我解决这个问题吗?

谢谢。

【问题讨论】:

    标签: python postgresql flask psycopg2


    【解决方案1】:

    您链接到的文档根本没有显示以这种方式使用 DictRow。也许您打算使用 DictCursor,文档确实显示以这种方式使用它。

    【讨论】:

    • 我不想争论,但是 "class psycopg2.extras.DictRow(cursor) - 允许按列名访问数据的行对象。"对我来说听起来像是我想要的东西。不过你的建议是对的,对我有帮助,谢谢。
    猜你喜欢
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 2021-02-12
    相关资源
    最近更新 更多