From "Programming Python" by Mark Lutz:
curs.execute("Select * FROM people LIMIT 0")
colnames = [desc[0] for desc in curs.description]
Answer from Setjmp on Stack OverflowFrom "Programming Python" by Mark Lutz:
curs.execute("Select * FROM people LIMIT 0")
colnames = [desc[0] for desc in curs.description]
Another thing you can do is to create a cursor with which you will be able to reference your columns by their names (that's a need which led me to this page in the first place):
import psycopg2
from psycopg2.extras import RealDictCursor
ps_conn = psycopg2.connect(...)
ps_cursor = psql_conn.cursor(cursor_factory=RealDictCursor)
ps_cursor.execute('select 1 as col_a, 2 as col_b')
my_record = ps_cursor.fetchone()
print (my_record['col_a'],my_record['col_b'])
>> 1, 2
def get_query_results_as_list_of_dicts(query):
"""
runs a query and returns the result as a dict rather than a tuple
:param query: SQL formatted string
:return: list of dictionary objects. one for each result returned from the database
"""
# Execute the query
cur.execute(query)
# Fetch all the rows as a list of dictionaries
list_of_dicts = [dict(row) for row in cur.fetchall()]
return list_of_dicts
You should use the RealDictCursor when creating the cursor for psycopg2.
import psycopg2
from psycopg2.extras import RealDictCursor
# Connect to the database
db = psycopg2.connect(
dbname="your_dbname",
user="your_username",
password="your_password",
host="your_host",
port="your_port"
)
# Create a cursor using RealDictCursor
cursor = db.cursor(cursor_factory=RealDictCursor)
query = f"SELECT * FROM your_table"
# Execute the query
cursor.execute(query)
data = cursor.fetchall()
for row in data:
print(row['id'])
print(row['column_name'])
# Close the cursor and connection
cursor.close()
db.close()
You need to use RealDictCursor, then you can access the results like a dictionary:
import psycopg2
from psycopg2.extras import RealDictCursor
connection = psycopg2.connect(user="...",
password="...",
host="...",
port="...",
database="...",
cursor_factory=RealDictCursor)
cursor = connection.cursor()
cursor.execute("SELECT * FROM user")
users = cursor.fetchall()
print(users)
print(users[0]['user'])
Output:
[RealDictRow([('user', 'dbAdmin')])]
dbAdmin
no need to call fetchall() method, the psycopg2 cursor is an iterable object you can directly do:
cursor.execute("SELECT * FROM user")
for buff in cursor:
row = {}
c = 0
for col in cursor.description:
row.update({str(col[0]): buff[c]})
c += 1
print(row["id"])
print(row["first_name"])
print(row["last_name"])
If what you want is a dataframe with the data from the db table as its values and the dataframe column names being the field names you read in from the db, then this should do what you want:
import psycopg2 as pq
cn = pq.connect('dbname=mydb user=me')
cr = cn.cursor()
cr.execute('SELECT * FROM test1;')
tmp = cr.fetchall()
# Extract the column names
col_names = []
for elt in cr.description:
col_names.append(elt[0])
# Create the dataframe, passing in the list of col_names extracted from the description
df = pd.DataFrame(tmp, columns=col_names)
The column names are available as cr.description[0][0], cr.description[1][0], etc. If you want it in exactly the format you show, you need to do some work to extract it and stick it in front of the result set.
