我在使用mySQL时遇到了这个问题。我的结果是[{'email': 'bernie@shrimp.com'}]
,但当我做email = results[0]['email']
时,我得到了TypeError: tuple indices must be integers or slices, not str
问题是当我在本地运行这个程序时,它工作得很好。我怎么得到bernie@shrimp.com
?
用户是一个表
代码:
cursor.execute('SELECT email FROM users WHERE username = %s', [attempted_username])
email_dict = cursor.fetchall()
print(email_dict)
session['email'] = email_dict[0]['email']
控制台:
[{'email': 'bernie@shrimp.com'}]
fetchall
返回元组列表。您需要按列的序号而不是名称来访问它:这可以与extras.DictCursor一起使用:
fetchall
的结果是元组列表,而不是dict
的列表。查询结果只有一个字段:位于索引0的电子邮件。
您可以这样重写代码:
或者,在你只有一个结果的情况下:
我想,你也可以使用:
相关问题 更多 >
编程相关推荐