简体   繁体   中英

Validating user details using sqlite3 and python

I created a database called finance.db and it contains a table named 'test'. The table takes 5 parameters including 'user' and 'password'. 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'. 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.

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. 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. Perhaps something like that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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