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


Question

Is there a way to retrieve SQL result column value using column name instead of column index in Python? I'm using Python 3 with mySQL. The syntax I'm looking for is pretty much like the Java construct:

Object id = rs.get("CUSTOMER_ID"); 

I've a table with quite a number of columns and it is a real pain to constantly work out the index for each column I need to access. Furthermore the index is making my code hard to read.

Thanks!

1
43
4/17/2012 4:51:37 PM

Accepted Answer

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.

79
4/17/2012 5:13:00 PM

This post is old but may come up via searching.

Now you can use mysql.connector to retrive a dictionary as shown here: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

Here is the example on the mysql site:

cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")

print("Countries in Europe:")
for row in cursor:
    print("* {Name}".format(Name=row['Name']

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon