Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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"
    try:
        cur.execute(getQuestionId)
        for row in cur.fetchall():
            print 'printing row'
            print row
            qIds.append(str(row['question_id']))
    except Exception, e:
        traceback.print_exc()
    return qIds

Printing what my method does:

Database version : 5.5.10 
getting all the question ids
printing row
(u'20090225230048AAnhStI',)
Traceback (most recent call last):
  File "YahooAnswerScraper.py", line 76, in questionIds
    qIds.append(str(row['question_id'][0]))
TypeError: tuple indices must be integers, not str
like image 303
add-semi-colons Avatar asked Sep 07 '12 20:09

add-semi-colons


People also ask

How do you fix tuple indices must be integers or slices not str?

The Python "TypeError: tuple indices must be integers or slices, not str" occurs when we use a string instead of an integer to access a tuple at a specific index. To solve the error, use the int() class to convert the string to an integer, e.g. my_tuple[int(my_str)] .

How do you fix tuple indices must be integers or slices not tuple?

The Python "TypeError: tuple indices must be integers or slices, not tuple" occurs when we use a tuple instead of an integer when accessing a tuple at index. To solve the error, correct the assignment or use a colon if trying to get a slice of a tuple.

How do you fix tuple index out of range?

The IndexError: tuple index out of range error occurs when you try to access an item in a tuple that does not exist. To solve this problem, make sure that whenever you access an item from a tuple that the item for which you are looking exists.

What are tuple indices?

Tuple indices are used to optimize searches that have 0 or more medial-search strings and 0 or 1 final-search strings.


2 Answers

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
like image 121
jjm Avatar answered Sep 18 '22 13:09

jjm


There are multiple cursor types in the MySQLdb module. The default cursor returns the data in a tuple of tuples. When we use a dictionary cursor, the data is sent in a form of Python dictionaries. This way we can refer to the data by their column names. Source

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb

con = mdb.connect('localhost', 'testuser', 'test623', 'testdb')

with con:

    cur = con.cursor(mdb.cursors.DictCursor)
    cur.execute("SELECT * FROM Writers LIMIT 4")

    rows = cur.fetchall()

    for row in rows:
        print row["Id"], row["Name"]
like image 35
Rafa Avatar answered Sep 20 '22 13:09

Rafa