+4 votes
in Programming Languages by (40.5k points)

I am trying to fetch rows from the PostgreSQL database using the psycopg2 module. The following code return correct values. However, it does not return the column names. Is there any way to get column names and values using the psycopg2 module?

conn = psycopg2.connect(dsn)

cur = conn.cursor()

cur.execute("SELECT * FROM meta")

cur.fetchmany()

1 Answer

+4 votes
by (348k points)
selected by
 
Best answer

You can use pandas' read_sql() function to get column names along with the values.

Here is an example:

import pandas as pd
conn = psycopg2.connect(dsn)
results = pd.read_sql("SELECT * FROM meta", conn)
print(results)

The above code will show you the name of the columns, too.


...