spechal.com | [spesh-uhl]

Nov/09

27

Python MySQL Associative Array

By default, the MySQLdb module to access a MySQL database returns the data as an integer indexed array. Sometimes this is not desirable and an associative array is preferred, such as the mysql_fetch_assoc function in PHP. In addition, we will be using the pprint module which is similar PHP’s print_r

Here is the Python equivalent:

import MySQLdb
import pprint
# connect to the database here
db = MySQLdb.connect(...)
c = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)
query = "SELECT `name`, `address` FROM `table`"
c.execute(query)
rows = c.fetchall()
c.close()
pprint.pprint(rows) # i.e. print_r($rows)

Hope that helps someone.

RSS Feed

No comments yet.

Leave a comment!

<<

>>

Find it!

Theme Design by devolux.org