如何在python3中使用psycopg2从postgres获取数据,包括列名

KbiR

我正在尝试使用 psycopg2 从 postgres 表中获取数据。这是我所做的。

import psycopg2


con = psycopg2.connect("host=localhost dbname=crm_whatsapp user=odoo password=password")
cur = con.cursor()
sql = """SELECT * from tbl_hospital;"""
db_cursor.execute(sql)
hospital_data = db_cursor.fetchall()
print('hospital_data',hospital_data)

输出是:

hospital_data [(1, 'hospital1', 1), (2, 'hospital2', 2), (3, 'hospital3', 3), (4, 'hospital4', 1)]

输出不包含克隆标头。我也需要那个。我怎么能得到那个。?

迈克布

游标中有元数据。

来自 M. Lutz 的“Python 编程”:

...
db_cursor.execute(sql)
colnames = [desc[0] for desc in db_cursor.description]

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用Flask,SQLAlchemy或psycopg2从Postgres中的游标中获取数据

如何在python psycopg2中使用ilike和通配符模式?

不能使用带有psycopg2的另一个python3容器中的postgres容器

如何在 Python 中使用 psycopg2 将空字符写入 bytea 列

如何在psycopg2中使用服务器端游标

如何在django和psycopg2中使用服务器端游标?

从Psycopg2中的架构获取数据

psycopg2使用列名而不是列号来获取行数据

如何在Python上使用“ pip”安装psycopg2?

如何在psycopg2中将列名作为参数传递?

如何使用 psycopg2 将数据插入 postgres 数据库

Python / postgres / psycopg2:获取刚刚插入的行的ID

如何在python3中使用正则表达式获取值

Psycopg2在Postgres数据库中插入python字典

Python3 psycopg2:使用RETURNING进行“无结果提取”

如何在python3中使用python2 input()函数?

如何在python3中使用Asterisk AGI?

如何在psycopg2连接池中使用“ INSERT”?

如何在psycopg2 select查询中使用字符串变量?

使用请求和psycopg2在Postgres中插入Json

使用psycopg2在postgres中调用CURRENT_TIMESTAMP()

使用psycopg2在postgres中执行插入

如何使用 python/psycopg2 中止/回滚待处理的 postgres 事务?

在psycopg2中使用带语句创建事务

使用Python中的psycopg2获取插入到Redshift表中的行的自动ID

如何使用psycopg2获取PostgreSQL版本?

使用psycopg2,如何获取“ INFO:”行?

Python Postgres psycopg2 ThreadedConnectionPool耗尽

psycopg2:如何使用psycopg2和python在冲突中进行插入和更新?