【发布时间】:2019-04-14 04:51:55
【问题描述】:
我在将用户输入与已使用用户名的数据库进行比较时遇到问题。数据库完全按照应有的方式工作,但似乎是一项简单的任务,但事实证明它比我想象的要困难得多。我想我错过了一些非常简单的东西!我没有从代码中得到错误代码,但是当用户名实际上在数据库中时,它不会打印“用户名被占用”。
到目前为止,我已经尝试了一个 for 循环来比较用户对数据库的输入,我已经尝试在数据库中创建一个用户名列表并遍历该列表以比较用户输入:
### check to see if the user is already in the database
import mysql.connector
# Database entry
mydb = mysql.connector.connect(
host='Localhost',
port='3306',
user='root',
passwd='passwd',#changed for help
database='pylogin'
)
searchdb = 'SELECT username FROM userpass'
mycursor = mydb.cursor()
mycursor.execute(searchdb)
username = mycursor.fetchall()
print(username)
user = input('username')
for i in username:
if user == username:
print('username is taken')
else:
print("did not work")
不起作用的输出:
[('Nate',), ('test',), ('test1',), ('test2',), ('n',), ('test4',)] username: n
('Nate',)
('test',)
('test1',)
('test2',)
('n',)
('test4',)
我希望上面的代码遍历每个数据库条目并将其与用户的输入进行比较,以验证用户名是否尚未被使用。它应该打印“用户名被占用”而不是打印“没有工作”。
【问题讨论】:
-
您好,您应该让数据库来完成这项工作。尝试这样的查询...“SELECT * FROM userpass WHERE username = :username (the variable you are checks for)” 然后,只需检查结果的行数。如果没有返回任何行,则表示用户名不在数据库中。如果您返回行,则意味着名称在其中。它将与您进行大量编码,并且您不必遍历结果。
标签: mysql python-3.x web-applications