Null-Hypothesis Null-Hypothesis - 1 month ago 21
MySQL Question

Python: tuple indices must be integers, not str when selecting from mysql table

I have following method that I select all the ids from table and append them to a list and return that list. But when execute this code I end up getting tuple indicies must be integers... error. I have attached the error and the print out along with my method:

def questionIds(con):
print 'getting all the question ids'
cur = con.cursor()
qIds = []
getQuestionId = "SELECT question_id from questions_new"
for row in cur.fetchall():
print 'printing row'
print row
except Exception, e:
return qIds

Printing what my method does:

Database version : 5.5.10
getting all the question ids
printing row
Traceback (most recent call last):
File "", line 76, in questionIds
TypeError: tuple indices must be integers, not str

jjm jjm

The python standard mysql library returns tuples from cursor.execute. To get at the question_id field you'd use row[0], not row['question_id']. The fields come out in the same order that they appear in the select statement.

A decent way to extract multiple fields is something like

for row in cursor.execute("select question_id, foo, bar from questions"):
    question_id, foo, bar = row