如何在 python3 中使用 psycopg2 从 postgres 获取数据,包括列名
How to fetch data from postgres including column name using psycopg2 in python3
我正在尝试使用 psycopg2 从 postgres table 获取数据。
这是我所做的。
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)]
输出不包含列header。我也需要那个。我怎样才能得到它?
光标中有元数据。
来自 M. Lutz 的 "Programming Python":
...
db_cursor.execute(sql)
colnames = [desc[0] for desc in db_cursor.description]
我正在尝试使用 psycopg2 从 postgres table 获取数据。 这是我所做的。
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)]
输出不包含列header。我也需要那个。我怎样才能得到它?
光标中有元数据。
来自 M. Lutz 的 "Programming Python":
...
db_cursor.execute(sql)
colnames = [desc[0] for desc in db_cursor.description]