1

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

2
  • BTW, please don't format SQL yourself. Use the second paramter of the execute method instead. Commented Oct 26, 2019 at 11:34
  • @back2thelotus Your code is vulnerable to SQL injection. Please read up on it and follow Matthias's suggestion so that your database doesn't get hacked. Commented Oct 26, 2019 at 11:40

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.