gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:51:05 25 4
gpt4 key购买 nike

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

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 语句中出现的顺序相同。

提取多个字段的一种不错的方法是

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

关于Python:从 mysql 表中选择时,元组索引必须是整数,而不是 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12325234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com