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

25,947

Solution 1

Please use dictionary cursor:

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

Solution 2

For me, this worked:

cursor = conn.cursor(dictionary=True)

Detailed example:

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

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

Related videos on Youtube

Ken
Author by

Ken

Updated on July 26, 2020

Comments

  • Ken
    Ken almost 4 years

    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)?

    • Gandi
      Gandi over 12 years
      I guess it's a duplicate of this one: stackoverflow.com/questions/2180226/…
    • varela
      varela over 12 years
      Maybe you need dictionary cursor?cursor = conn.cursor (MySQLdb.cursors.DictCursor)
    • Ken
      Ken over 12 years
      If you want, make this link an answer which I'll accept.
    • agf
      agf over 12 years
      If you don't have enough reputation to vote to close, flag the answer, select "other", and just put in "duplicate" and the URL. Don't post an answer that is just a link to a duplicate.
  • The EasyLearn Academy
    The EasyLearn Academy over 2 years
    it is working with mysql.connector library.