首页 > 解决方案 > 数据库无法将输入与其数据进行比较

问题描述

我想做一个可以使用 sqlite3 的小登录页面。好吧,如果我使用用户名和密码登录,即使我没有将它们添加到数据库中,它也会始终让我通过。
数据库类的方法应该照顾用户的数据,如果它是已知的或未知的。
另外我添加我的小测试来看看,如果数据库真的是空的。

class Database:

    def __init__(self):
        # Connect to file
        self.connection = sqlite3.connect(
            r"C:\Users\Anonym\Documents\Data.txt",
            check_same_thread=False)

        # Create Cursor
        self.c = self.connection.cursor()

        # Table already created?
        try:
            self.c.execute("SELECT * FROM Users")

        # Table doesn't exist
        except:
            self.c.execute("CREATE TABLE Users(User VARCHAR(20), Password VARCHAR(100))")        

    def UserInDatabase(self, name: str, password: str) -> bool:
        """
        Is the user already in the database?
        Yes => True
        No => False
        """
        password = hashlib.sha384(password.encode("utf-8")).digest()
        password = hashlib.sha384(password.encode("utf-8")).digest()

        # ---------------------------------------------------------
        # !!! Why does it always pass the try - clause? !!!
        try:
            self.c.execute("SELECT * FROM Users WHERE User = ?;", (name,))
            self.c.execute("SELECT * FROM Users WHERE Password = ?", (password, ))
            return True

        except Exception:
            # User is unkown
            return False
        # ---------------------------------------------------------
    (...)

我的测试:

if __name__ == "__main__":
    Database = Database()

    # Database is emtpy
    print(list(Database.c.execute("SELECT * FROM Users")))

    # Returns "True" although nobody is in the database?
    print(Database.UserInDatabase("Somebody", "GoodPassword"))

    # Exit Database
    Database.close()

它的输出是:

[]
True

我期望输出:

[]
False

因为数据库是空的,但它仍然返回True
为什么“激活” except 子句不会发生错误?

标签: pythonpython-3.xsqlite

解决方案


推荐阅读