Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, MySQL and cursors that fetch maps [duplicate]

Tags:

python

mysql

After executing a query statement on a MySQL database connection, I perform:

rows = cursor.fetchall()

This gives an array of arrays. I'd like to have an array of dictionaries, where each dictionary takes its keys from the requested column names of my table and associates the values from the table.

How do I do this?

like image 504
SK9 Avatar asked Dec 07 '22 17:12

SK9


1 Answers

Well, you forgot to mention which mysql library you're using.

  • If using oursql (which I recommend, it is certainly the best one), use oursql's DictCursor. Example:

    conn = oursql.connect(...)
    curs = conn.cursor(oursql.DictCursor)
    
  • If using MySQLdb (why?) Use MySQLdb's DictCursor. Example:

    conn = MySQLdb.connect(..., cursorclass=MySQLdb.cursors.DictCursor) 
    curs = conn.cursor() 
    

Doing that will give you a cursor that returns dicts for each row. Remember to not have duplicate rownames in your query.

like image 127
nosklo Avatar answered Dec 10 '22 12:12

nosklo