简体   繁体   English

使用 sqlite3 和 python 验证用户详细信息

[英]Validating user details using sqlite3 and python

I created a database called finance.db and it contains a table named 'test'.我创建了一个名为 Finance.db 的数据库,它包含一个名为“test”的表。 The table takes 5 parameters including 'user' and 'password'.该表采用 5 个参数,包括“用户”和“密码”。 A user is already inserted into the table.一个用户已经插入到表中。

I would like the user to be able to log in by providing their username and password and matching that against the database table 'test'.我希望用户能够通过提供他们的用户名和密码并将其与数据库表“test”匹配来登录。 If the table contains the correct username and password it allows the user to log in.如果该表包含正确的用户名和密码,则允许用户登录。

Here is how I imagine it would work:这是我想象的工作方式:

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)

Unfortunatelly it always returns 'not in db', even if correct details are inserted.不幸的是,它总是返回“不在数据库中”,即使插入了正确的细节。 I'm not sure what I am missing, but I suspect that my if statement is simply incorrect, but it does not result in a syntax or other error.我不确定我错过了什么,但我怀疑我的 if 语句完全不正确,但它不会导致语法或其他错误。

UPDATE:更新:

I solved the problem by extracting the information that I require from a tuple and then storing its value in a variable.我通过从元组中提取我需要的信息然后将其值存储在变量中来解决这个问题。 Here is what I changed:这是我改变的:

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

In this part of code在这部分代码中

for i in check:
    if username and password in check

I suppose that check is a list of tuples that represents all the query matched rows in the table.我想该check是一个元组列表,表示表中所有查询匹配的行。 So i is a tuple and you should compare your variables with the specific positions of the tuple which correspond to the fields username and password.所以i是一个元组,你应该将你的变量与对应于字段用户名和密码的元组的特定位置进行比较。 Perhaps something like that:也许是这样的:

for i in check:
    if username == i[0] and password == i[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM