如何使用psycopg2客户端从select查询中获取col头



我有这个python3代码:

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

其中"code"具有选择查询语句

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

意思是如果我说

Select col1, col2 from table Where some_condition;

我希望我的"行"列表具有类似[['col1','col2'],[some_val_for_col1],some_val_fol_col2]….]的内容。获取这些col头的任何其他方法也可以,但"code"中的select查询不应该更改。

您必须执行两个命令

  1. curr.execute("Select*FROM people LIMIT 0"(colnames=[desc[0]用于curs.description]中的desc
  2. curr.execute(代码(

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

相关内容

最新更新