Python: 'NoneType' 对象不可下标'错误

标签 python python-3.x nonetype

我是 Python 数据库新手,因此为了练习一些关键技能,我正在构建一个登录屏幕,将用户名和散列密码写入数据库,然后根据数据库中的内容检查用户的输入。但是,当尝试从数据库中提取用户名和密码并将其存储在变量中时,我不断收到“'NoneType'对象不可下标”错误。

我该如何解决这个问题?

这是我的程序中包含错误的函数

def login():
usernameAttempt = input("Enter your username: ")
passwordAttempt = input("Enter your password: ")

usernameSql = """SELECT Username FROM Details WHERE Password = '%s'""" % (passwordAttempt) # Selecting username in database
cur.execute(usernameSql)
usernameSql = cur.fetchone()
userFetched = usernameSql[0] # Pulling the item from the database

passwordSql = """SELECT Password FROM Details WHERE Username = '%s'""" % (usernameAttempt)
cur.execute(passwordSql)
passwordSql = cur.fetchone()
passFetched = passwordSql[0]

dbPassword, dbSalt = passFetched.split(":")

return dbPassword, dbSalt, passwordAttempt, usernameAttempt, userFetched, passFetched

我希望变量 userFetched 和 passFetched 被分配用户名和密码列中索引 0 处保存的值,但错误消息如下:

回溯(最近一次调用最后一次):

文件“C:\Users\laure\Documents\Login screen.py”,第 57 行,位于 dbPassword、dbSalt、passwordAttempt、usernameAttempt、userFetched、passFetched = 登录()

文件“C:\Users\laure\Documents\Login screen.py”,第 34 行,登录中 userFetched = usernameSql[0] # 从数据库中提取项目 类型错误:“NoneType”对象不可订阅

最佳答案

您的选择用户名查询未返回任何行。所以结果集是空的,没有什么可获取的。因此,您的 fetchone 调用返回 None 而不是您期望的行元组。

关于Python: 'NoneType' 对象不可下标'错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59963211/

相关文章:

python - 根据文件基名对文件夹和子文件夹中的所有文件进行排序

python - 连接 Pandas 日期时间

python - 对于每个原始类型,Python 将什么视为 True 或 False?

python - 调用 '.get()' 问题返回“无”

python - 时钟程序继承帮助 - Python

python - 如何在一行中读取 A 列到 B 列的所有字符

python - 什么是堆队列?

python-3.x - 如何在 boto 程序中指定 aws 区域?

python - django 计算中的 0.01 differecene

python - 无内存位置