0

I am trying to fetch data from a postgres table using psycopg2. Here is what i have done.

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)

And the output is:

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

The output is not contains the cloumn header. I need that too. How can i get that.?

1 Answer 1

1

The cursor has the metadata in it.

From "Programming Python" by M. Lutz:

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

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.