Python:从 mysql 表中选择时,元组索引必须是整数,而不是 str

2022-01-20 00:00:00 python tuples mysql

我有以下方法,我从表中选择所有 id 并将它们附加到列表并返回该列表.但是当执行这段代码时,我最终得到元组索引必须是整数......错误.我附上了错误和打印出来的方法:

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

打印我的方法的作用:

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

推荐答案

python标准mysql库从cursor.execute返回元组.要获取 question_id 字段,您将使用 row[0],而不是 row['question_id'].字段的出现顺序与它们在 select 语句中出现的顺序相同.

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

相关文章