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

tuple indices must be integers or slices, not str

我在使用 mySQL 时遇到了这个问题 运行。我的结果 = [{'email': 'bernie@shrimp.com'}] 但我在做 email = results[0]['email']

时得到 TypeError: tuple indices must be integers or slices, not str

问题是,当我在本地 运行 时,它工作得很好。我如何获得 bernie@shrimp.com

用户是 table

代码:

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 的结果是一个元组列表,而不是 dict 的列表。

您的查询结果只有一个字段:email at index 0.

您可以这样重写代码:

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

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

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

我想,你也可以使用:

row = cursor.one()

fetchall returns 元组列表。您需要按列序数而不是其名称来访问它:

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

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

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