Python: 'NoneType' object is not subscriptable' error [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-30 09:17:25

问题


I'm new to databases in Python, so to practice some key skills I'm building a login screen that writes usernames and hashed passwords to the database, and then checks the user's inputs against what's in the database. However, when trying to pull the usernames and passwords from the database and storing them in variables, I keep getting the "'NoneType' object is not subscriptable" error.

How can I fix this?

This is the function from my program that contains the error

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

I expected the variables userFetched and passFetched to be assigned the values held at indexes 0 in the username and password columns, but the error messages are as follows:

Traceback (most recent call last):

File "C:\Users\laure\Documents\Login screen.py", line 57, in dbPassword, dbSalt, passwordAttempt, usernameAttempt, userFetched, passFetched = login()

File "C:\Users\laure\Documents\Login screen.py", line 34, in login userFetched = usernameSql[0] # Pulling the item from the database TypeError: 'NoneType' object is not subscriptable


回答1:


Your select Username query is returning no rows. So the result set is empty and there is nothing to fetch. So your fetchone call returns None instead of the row tuple you expect.




回答2:


When tyour query return 0 rows fetchone will return 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


来源:https://stackoverflow.com/questions/58570317/python-nonetype-object-is-not-subscriptable-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!