python - 数据库无法将输入与其数据进行比较
问题描述
我想做一个可以使用 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 子句不会发生错误?
解决方案
推荐阅读
- html - 如何将列出页数的分页器下拉菜单的字体更改为更大?
- python - 第三方 API 调用后 Django 无法再找到 base.html
- sql - 根据 TypeID 创建列
- java - Java Producer Consumer - 为什么不是简单的 FixedThreadPool?
- dynamics-crm - 当用户登录时,我可以在 CRM 中自动创建 Power Geo Logging 配置实体(powergeologgingconfiguration)吗?
- url - 如何在 jasper 报告中创建文件下载超链接
- jquery - 数据表工作不正常。$(...).DataTable 不是函数
- javascript - chai-as-promised 拒绝不会失败测试,而只会打印警告
- reactjs - 在 Create-react-app 中将 sass 文件导入另一个 sass 文件不起作用
- php - 在使用 docker-compose 从 YML 构建服务器/网站的开发副本后,我遇到了与 dotenv 相关的致命 PHP 错误?