我正在从保存和检查文本文档上的登录文件过渡到 SQL 数据库。在我当前的解决方案中,我已经开始工作,我可以检查文件中的用户名和密码,然后报告用户名或密码是否分别正确。我的SQL实现代码如下:
def check_login_on_db():
user = UserSignUpDetails(None, None, log_in_window_username_entry.get(),
log_in_window_password_entry.get())
enteredUsername = user.username
enteredPassword = user.password
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
cursor.execute('SELECT * from SignUpDetails where username="%s"'%(enteredUsername))
values = cursor.fetchall()
for i in values:
if values[i] == None:
log_in_additional_info.config(text="This username is incorrect")
conn.close()
else:
if values[i] == enteredUsername:
if values[i+1] != enteredPassword:
log_in_additional_info.config(text="The password is incorrect")
conn.close()
else:
log_in_additional_info.config(text="")
conn.close
我将不胜感激。
如果我输入我知道有误的详细信息,我预计会收到错误消息,但事实并非如此。 如果我使用这个实现,我会让它工作并显示错误,但我更愿意让它在它告诉我哪个部分出错的地方工作:
cursor.execute('SELECT * from SignUpDetails where username="%s"'%(enteredUsername))
if cursor.fetchone():
log_in_additional_info.config(
text="Success")
else:
log_in_additional_info.config(
text="Incorrect username or password")
我认为在这里使用变量
i
来表示一行会让事情变得有点混乱。让我们重命名一些变量以帮助增加一些清晰度。
在我们清理东西的同时,我将进行一些额外的更改。首先,SQL 不喜欢双引号,所以让我们翻转引号,让 SQL 看到单引号。其次,我将使用 for 语句的
else
子句(又名 no_break)来处理没有找到具有匹配密码的行的情况。
最后,顺便说一句,您的代码目前处理两个帐户理论上可以具有相同共享用户名的情况。那真的是你想要的吗?如果不是,你可以做
fetchone()
然后摆脱 for
循环:
注意,未经测试,仅来自我的头顶。
def check_login_on_db():
user = UserSignUpDetails(
None,
None,
log_in_window_username_entry.get(),
log_in_window_password_entry.get()
)
enteredUsername = user.username
enteredPassword = user.password
with sqlite3.connect("database.db") as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT * from SignUpDetails where username = '%s'" % (enteredUsername))
rows = cursor.fetchall() # can two accounts actually have the same username?
if not rows:
log_in_additional_info.config(text="This username is incorrect")
return
for row in rows:
if row[2] == enteredPassword:
log_in_additional_info.config(text="")
break
else:
log_in_additional_info.config(text="The password is incorrect")
如果你不喜欢这里的
else
子句那么在这种情况下,你也可以这样做:
def check_login_on_db():
user = UserSignUpDetails(
None,
None,
log_in_window_username_entry.get(),
log_in_window_password_entry.get()
)
enteredUsername = user.username
enteredPassword = user.password
with sqlite3.connect("database.db") as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT * from SignUpDetails where username = '%s'" % (enteredUsername))
rows = cursor.fetchall() # can two accounts actually have the same username?
if not rows:
log_in_additional_info.config(text="This username is incorrect")
return
for row in rows:
if row[2] == enteredPassword:
log_in_additional_info.config(text="")
return
log_in_additional_info.config(text="The password is incorrect")