Ken
Ken

Reputation: 31161

Python, MySQL and SELECT output to dictionary with column names for keys

I have a MySQL table on which I'm executing SELECT statements within Python.

Is there anything out of the Python MySQLdb API that will, via the cursor, output an array of dictionaries whose keys are the column names (and values are those in the returned rows)?

Upvotes: 36

Views: 40550

Answers (2)

DaWe
DaWe

Reputation: 1702

For me, this worked:

cursor = conn.cursor(dictionary=True)

Detailed example:

import mysql.connector # pip install mysql-connector-python

conn = mysql.connector.connect(host="localhost", user="user", passwd="pass", database="dbname")
cursor = conn.cursor(dictionary=True)
sql = "SELECT * FROM `table` WHERE 1"
cursor.execute(sql)
rows = cursor.fetchall()
for row in rows:
    row["col"]

Upvotes: 52

varela
varela

Reputation: 1331

Please use dictionary cursor:

cursor = conn.cursor (MySQLdb.cursors.DictCursor)

Upvotes: 39

Related Questions