我创建了一个名为finance.db的数据库,其中包含一个名为“ test”的表。该表采用5个参数,包括“用户”和“密码”。用户已经被插入表中。
我希望用户能够通过提供用户名和密码并将其与数据库表“ test”进行匹配来登录。如果表中包含正确的用户名和密码,则允许用户登录。
这是我想像的效果:
import sqlite3
user_name = input('Enter username: ')
user_password = input('Enter password:')
def login_details(username, password):
connection = sqlite3.connect('finance.db')
cursor = connection.cursor()
cursor.execute('SELECT * FROM test')
check = cursor.fetchall()
for i in check:
if username and password in check:
print('works')
else:
print('not in db')
login_details(username=user_name, password=user_password)
不幸的是,即使插入正确的详细信息,它也始终返回“不在db中”。我不确定我缺少什么,但是我怀疑我的if语句根本不正确,但是不会导致语法或其他错误。
更新:
我解决了这个问题,方法是从元组中提取所需的信息,然后将其值存储在变量中。这是我更改的内容:
for i in check:
user_name_input = i[1]
user_pass_input = i[2]
if user_name_input != username and user_pass_input != password:
print('not in db')
else:
print('in db')
答案 0 :(得分:1)
在这部分代码中
for i in check:
if username and password in check
我假设check
是一个元组列表,表示表中所有查询匹配的行。因此i
是一个元组,您应该将变量与元组的特定位置(对应于用户名和密码)进行比较。也许像这样:
for i in check:
if username == i[0] and password == i[1]