Python: tuple indices must be integers, not str when selecting from mysql table(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python:从 mysql 表中选择时,元组索引必须是整数,而不是 str
基础教程推荐
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01