本文介绍了Python:“NoneType"对象不可下标"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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):

文件C:\Users\laure\Documents\Login screen.py",第 57 行,在dbPassword, dbSalt, passwordAttempt, usernameAttempt, userFetched, passFetched = login()

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

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

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

推荐答案

当你的查询返回 0fetchone 将返回 None:

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

这篇关于Python:“NoneType"对象不可下标"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 21:50