0

Is there a way to retrieve SQL result column value using column name instead of column index in Python?

result = `select name, deptname from employee;`

I tried below one:

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["deptname"])

Here I got an error like:

TypeError: tuple indices must be integers, not str

Any help will be awesome?

2 Answers 2

2

Actually you are getting what you wanted. You just need to use the row not as a dictionary but as a tuple. That means that the indices are numbers, not strings. Try

print "%s, %s" % (row[0], row[1])

instead

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, but the OP specifically asks Is there a way to retrieve SQL result column value using column name instead of column index in Python?..meaning the OP actually wants dictionary access to the table rows.
1

You are not correctly specifying that you need a dictionary cursor. Do that when you call the connect() method, set the cursorclass:

import MySQLdb

conn = MySQLdb.connect(user='user', 
                       passwd='password', 
                       db='db_name', 
                       cursorclass=MySQLdb.cursors.DictCursor) 
cursor = conn.cursor()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.