简体   繁体   English

如何在 python 中搜索 SQL 列表以检查用户名是否与用户输入匹配?

[英]How do I search a SQL List inside of python to check if the username matches a user input?

So I am making a login page, and I need to compare the username of an SQL list to the user input.所以我正在制作一个登录页面,我需要将 SQL 列表的用户名与用户输入进行比较。 I will also use the answer for the password.我还将使用密码的答案。 This is what I have tried and it returns false.这是我尝试过的,它返回 false。

list_of_users = [('joe@gmail.com', 'qwerty'), ('jeremy', '123')]

for i in list_of_users:
    if i == 'joe@gmail.com':
        print("True")
    else:
        print("False")

The list_of_users is there to simulate what the SQL gives when you do cursor.fetchall() on an SQL database.当您在 SQL 数据库上执行 cursor.fetchall() 时,list_of_users 用于模拟 SQL 给出的结果。 Any input would be appriciated!任何输入都会被应用!

Because the elements of your list are tuples of two elements.因为列表的元素是两个元素的元组。 So each element has two in turn.所以每个元素依次有两个。 See the definition in the official documentation of Data Structures - Tuples and Sequences .参见Data Structures-Tuples and Sequences官方文档中的定义。

If you wanted to fix your code, you would then simply add a second element to the for loop:如果你想修复你的代码,你只需在 for 循环中添加第二个元素:

list_of_users = [('joe@gmail.com', 'qwerty'), ('jeremy', '123')]

for email, pwd in list_of_users:
    if email == 'joe@gmail.com':
        print("True")
    else:
        print("False")

But this approach has a fundamental flaw for your use case .但是这种方法对于您的用例有一个根本性的缺陷 You want to print N times 'false'?你想打印 N 次 'false'? Just iterate until the mail is found and stop.只需迭代直到找到邮件并停止。

This is an example toy code:这是一个示例玩具代码:

list_of_users = [('joe@gmail.com', 'qwerty'), ('jeremy', '123')]


def login(email: str, pwd: str, list_of_users: [()]) -> bool:
    for db_email, db_pwd in list_of_users:
         if (email == db_email) and (pwd == db_pwd):
             return True
    return False


print(login('jeremy', '123', list_of_users))  # True
print(login('jeremy', '456', list_of_users))  # False

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

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