我试图从数据库中提取数据并将它们分配给不同的列表。 这个特定的错误给了我很多麻烦“TypeError:元组索引必须是整数,而不是str” 我试着把它转换成浮子等,但没有成功。
代码如下
conn=MySQLdb.connect(*details*)
cursor=conn.cursor()
ocs={}
oltv={}
query="select pool_number, average_credit_score as waocs, average_original_ltv as waoltv from *tablename* where as_of_date= *date*"
cursor.execute(query)
result=cursor.fetchall()
for row in result:
print row
ocs[row["pool_number"]]=int(row["waocs"])
oltv[row["pool_number"]]=int(row["waoltv"])
打印语句的输出示例如下:
('MA3146', 711L, 81L)
('MA3147', 679L, 83L)
('MA3148', 668L, 86L)
这正是我得到的错误:
ocs[row["pool_number"]]=int(row["waocs"])
TypeError: tuple indices must be integers, not str
任何帮助都将不胜感激!谢谢大家!
就像错误所说的,
row
是一个元组,因此不能执行row["pool_number"]
。您需要使用索引:row[0]
。TL;DR:在
MySQLdb.connect
的末尾添加参数cursorclass=MySQLdb.cursors.DictCursor
。我有一个工作代码和数据库移动,我必须改变主机/用户/通行证。更改后,我的代码停止工作,并开始出现此错误。仔细检查后,我将连接字符串复制粘贴到一个有额外指令的地方。旧的代码读起来像:
替换为:
最后的参数
cursorclass=MySQLdb.cursors.DictCursor
使python允许我使用列名作为索引来访问行。但糟糕的复制粘贴消除了这一点,产生了错误。因此,作为已经提出的解决方案的替代方案,您还可以添加此参数,并按照最初需要的方式访问行。^_^我希望这能帮助别人。
问题是如何访问
row
特别是
row["waocs"]
和row["pool_number"]
的ocs[row["pool_number"]]=int(row["waocs"])
如果您查找找到的
fetchall()
的official-documentation。因此,您必须使用
row[__integer__]
访问行的值,如row[0]
相关问题 更多 >
编程相关推荐