元组索引必须是整数或切片,而不是s

2024-04-29 17:00:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用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'}]

Tags: integerscomemailmysqlusernamebecursorresults
3条回答

fetchall返回元组列表。您需要按列的序号而不是名称来访问它:

session['email'] = email_dict[0][0]

这可以与extras.DictCursor一起使用:

cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
for fields in cur:
   print(fields['column_name'])

fetchall的结果是元组列表,而不是dict的列表。

查询结果只有一个字段:位于索引0的电子邮件。

您可以这样重写代码:

rows = cursor.fetchall()
for row in rows:
    email = row[0]

或者,在你只有一个结果的情况下:

session['email'] = rows[0][0]

我想,你也可以使用:

row = cursor.one()

相关问题 更多 >