Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: use mysqldb to import a MySQL table as a dictionary?

Anyone know how I can use mysqldb to turn a MySQL table, with lots of rows, into a list of dictionary objects in Python?

I mean turning a set of MySQL rows, with columns 'a', 'b', and 'c', into a Python object that that looks like this:

data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 }, { 'a':'Q', 'b':(1, 4), 'c':5.0 }, { 'a':'T', 'b':(2, 8), 'c':6.1 } ] 

Thanks :)

like image 626
AP257 Avatar asked Feb 01 '10 21:02

AP257


People also ask

What is MySQLdb in Python?

MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2. 0 and is built on top of the MySQL C API. Packages to Install mysql-connector-python mysql-python.


1 Answers

MySQLdb has a separate cursor class for this, the DictCursor. You can pass the cursor class you want to use to MySQLdb.connect():

import MySQLdb.cursors MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor) 
like image 65
Thomas Wouters Avatar answered Sep 29 '22 03:09

Thomas Wouters