Python: Returning Rows as Dicts in MySQLdb

Do you want to return a row of data from your database as a dict rather than a tuple? Using MySQLdb? Then here’s how you do it. The traditional way to retrieve a row from a table is;

>>> import MySQLdb
>>> myDb = MySQLdb.connect(user=’andy47′, passwd=’password’, db=’db_name’)
>>> myCurs = myDb.cursor()
>>> myCurs.execute(“SELECT columna, columnb FROM tablea”)
>>> firstRow = myCurs.fetchone()
>>> firstRow
(‘first value’, ‘second value’)

But using the DictCursor cursorclass we get;

>>> import MySQLdb
>>> import MySQLdb.cursors
>>> myDb = MySQLdb.connect(user=’andy47′, passwd=’password’, db=’db_name’, cursorclass=MySQLdb.cursors.DictCursor)
>>> myCurs = myDb.cursor()
>>> myCurs.execute(“SELECT columna, columnb FROM tablea”)
>>> firstRow = myCurs.fetchone()
{‘columna’:’first value’, ‘columnb’:’second value’}

Note the extra import at the beginning, without it Python doesn’t know about MySQLdb’s cursors module. You should also be wary of guessing the order that the items in each row of the DictCursor are returned in. There is no guarantee, for instance, that “columna” will always be the first key and “columnb” the second. When using the DictCursor you should always access values directly by their key. When using the normal cursor class you can access the returned values in sequence (make sure never to use “SELECT *”) as that’s the only way you can associate a value with the column it has come from.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s