How to retrieve SQL result column value using column name in Python?

The MySQLdb module has a DictCursor:

Use it like this (taken from Writing MySQL Scripts with Python DB-API):

cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT name, category FROM animal")
result_set = cursor.fetchall()
for row in result_set:
    print "%s, %s" % (row["name"], row["category"])

edit: According to user1305650 this works for pymysql as well.

Leave a Comment