【问题标题】:How to get the col headers from a select query using psycopg2 client?如何使用 psycopg2 客户端从选择查询中获取 col 标头?
【发布时间】:2021-05-28 18:14:35
【问题描述】:

我有这个 python3 代码:

conn = psycopg2.connect( ... )
curr = conn.cursor()
curr.execute(code)
rows = curr.fetchall()

'code' 有选择查询语句的地方

执行此操作后,“行”列表将仅包含选定行值的列表。如何运行 'curr.execute' 以同时获得相应的 col 标头?

如果我说的意思

Select col1, col2 from table Where some_condition;

我希望我的“行”列表包含 [['col1', 'col2'], [some_val_for_col1, some_val_for_col2] ....]。获取这些 col 标头的任何其他方式也可以,但“代码”中的选择查询不应更改。

【问题讨论】:

  • 找到解决方案:使用字典光标。首先导入 psycopg2 和 psycopg2.extras。然后在上面的代码中将 'curr = conn.cursor()' 更改为 'curr = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)'。然后使用 'for key in dict(rows[0]): print(key)' --> 这将打印所有 col 标题。确保您有正确的缩进并且“行”不是一个空列表。

标签: postgresql psycopg2


【解决方案1】:

你必须执行 2 个命令

  1. curr.execute("Select * FROM people LIMIT 0") colnames = [desc[0] for desc in curs.description]
  2. curr.execute(code)

您可以按照https://kb.objectrocket.com/postgresql/get-the-column-names-from-a-postgresql-table-with-the-psycopg2-python-adapter-756中提到的步骤进行操作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 2015-05-10
    • 2015-10-09
    • 2015-08-26
    相关资源
    最近更新 更多