Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 772
SK9 Avatar asked Sep 01 '11 09:09

SK9


People also ask

How do I get column names in Python using SQL?

Approach: Connect to a database using the connect() method. Create a cursor object and use that cursor object created to execute queries in order to create a table and insert values into it. Use the description keyword of the cursor object to get the column names.

How can I get only column names from a table in MySQL?

You can list a table's columns with the mysqlshow db_name tbl_name command. The DESCRIBE statement provides information similar to SHOW COLUMNS .

What does cursor Fetchall return?

fetchall() Method. The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list.

What is dictionary cursor?

a line on a computer screen that moves to show the point where work is being done: You can move the cursor either by using the mouse or by using the arrow keys on the keyboard. Compare. pointer. Computer hardware.


1 Answers

Please use dictionary cursor:

cursor = conn.cursor (MySQLdb.cursors.DictCursor) 
like image 116
varela Avatar answered Oct 16 '22 23:10

varela