Python, MySQL, and cursors that retrieve maps

After executing the query statement in the MySQL database connection, I execute:

rows = cursor.fetchall() 

This gives an array of arrays. I would like to have an array of dictionaries, where each dictionary extracts keys from the requested column names of my table and binds the values ​​from the table.

How to do it?

+4
source share
1 answer

Well, you forgot to mention which mysql library you use.

  • If you are using oursql (which I recommend is definitely the best), use oursql DictCursor . Example:

     conn = oursql.connect(...) curs = conn.cursor(oursql.DictCursor) 
  • If you use MySQLdb (why?) Use MySQLdb DictCursor . Example:

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

Doing this will give you a cursor that returns dicts for each row. Remember that your query does not need to duplicate the names of the growths.

+14
source

Source: https://habr.com/ru/post/1387856/


All Articles