Python:从mysql表中选择时,元组索引必须是整数,而不是str [英] Python: tuple indices must be integers, not str when selecting from mysql table

查看:80
本文介绍了Python:从mysql表中选择时,元组索引必须是整数,而不是str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法,我从表中选择所有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

这篇关于Python:从mysql表中选择时,元组索引必须是整数,而不是str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆