I want to be able to do something like the code below (which is PHP):
while($row = mysql_fetch_array($result)){
$name = $row['name'];
$event = $row['event'];
in python. So getting an element by its index. What is the best way?
I want to be able to do something like the code below (which is PHP):
while($row = mysql_fetch_array($result)){
$name = $row['name'];
$event = $row['event'];
in python. So getting an element by its index. What is the best way?
Yes, using dictionaries, which are built in types.
d = {'name': 'user'}
print d['name']
user
You use the DictCursor object from the MySQLdb package. This will produce a dictionary (mapping) in the result set rather than the usual tuples.
import MySQLdb
from MySQLdb import cursors
def fetchallmap(self, q, *args):
"""Fetch all rows into a dictionary.
"""
curs = self._connection.cursor(cursors.DictCursor)
curs.execute(q, args)
res = curs.fetchall()
curs.close()
self._connection.commit()
return res
This will return a list of dictionaries (mappings). If you just want one row, just substitute fetchoone
instead of fetchall
.
def fetchonemap(self, q, *args):
"""Fetch one row into a dictionary.
"""
curs = self._connection.cursor(cursors.DictCursor)
curs.execute(q, args)
res = curs.fetchone()
curs.close()
self._connection.commit()
return res