Python:“ NoneType”对象不可下标”错误

时间:2019-10-26 11:25:24

标签: 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 = login()

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

2 个答案:

答案 0 :(得分:0)

您的select Username查询未返回任何行。因此,结果集为空,没有任何可获取的内容。因此,您的fetchone调用将返回None,而不是您期望的行元组。

答案 1 :(得分:0)

查询返回0fetchone时将返回None

usernameSql = """SELECT Username FROM Details WHERE Password = '%s'""" % (passwordAttempt) # Selecting username in database
cur.execute(usernameSql)
usernameSql = cur.fetchone()
# check if the query return at least one record
if usernameSql:
    userFetched = usernameSql[0] 
else:
   # show a error or somthing