我在将用户输入与已使用用户名的数据库进行比较时遇到问题。数据库完全按照它应该的方式工作,但看起来很简单的任务比我想象的要困难得多。我想我错过了一些非常简单的东西!我没有从代码中得到错误代码,但当用户名实际上在数据库中时,它不会打印"username is taken“。
到目前为止,我已经尝试了一个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',)我希望上面的代码遍历每个数据库条目,并将其与用户的输入进行比较,以验证用户名是否尚未被使用。它应该打印"username is taken“,而不是"did work”。
发布于 2019-04-14 13:45:19
欢迎来到Stack Overflow Nate!
您可以使用:
mycursor.execute("SELECT * FROM userpass WHERE username = ?", [(user)])
results = cursor.fetchall()创建一个名为‘result’的变量,该变量存储userpass数据库表中记录的所有(*)列值,其中记录的用户名等于用户变量的值。
然后可以使用if语句:
if results:如果results变量的值为AKA (如果存在一个用户名等于表中user变量的值的记录),则运行该函数;如果采用该用户名,则运行该函数。
此if语句然后可以在运行时打印'username is taken‘
完整的代码:
import mysql.connector
# Database entry
mydb = mysql.connector.connect(
host='Localhost',
port='3306',
user='root',
passwd='passwd',#changed for help
database='pylogin'
)
user = input('username')
mycursor.execute("SELECT * FROM userpass WHERE username = ?", [(user)])
results = cursor.fetchall()
if results:
print('username is taken')
else:
print("did not work")https://stackoverflow.com/questions/55672060
复制相似问题