【问题标题】:Comparing user input to usernames in database将用户输入与数据库中的用户名进行比较
【发布时间】: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


【解决方案1】:

欢迎来到 Stack Overflow Nate!

你可以使用:

mycursor.execute("SELECT * FROM userpass WHERE username = ?", [(user)])
results = cursor.fetchall()

创建一个名为“results”的变量,用于存储 userpass 数据库表中记录的所有 (*) 列值,其中记录的用户名等于用户变量的值。

然后您可以使用 if 语句:

if results:

如果结果变量有一个值(如果有一条用户名与表中用户变量的值相等的记录)则运行 AKA,如果使用了用户名。

这个 if 语句可以在运行时打印'用户名被占用'

完整代码:

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")

【讨论】:

  • 嗨,汤姆,感谢您的快速回复。在尝试您建议的代码时,我仍然必须为 mycursor 定义一个值。我也收到错误“mysql.connector.errors.ProgrammingError:并非所有参数都在 SQL 语句中使用”
【解决方案2】:

edit* 将此代码添加到程序的其余部分并进行测试时,我发现它给出了每次使用的用户名结果,即使它是新用户名也是如此。如果您有任何解决此问题的建议,我愿意接受。我将继续为此工作,并在程序正常运行时发布结果。

感谢你们的帮助,我确实找到了我想要的回复!

### check to see if user is already in database
import mysql.connector


# Database entry
mydb = mysql.connector.connect(
    host='Localhost',
    port='3306',
    user='root',
    passwd='passwd',#changed for help
    database='pylogin'

)
mycursor = mydb.cursor()
user = input('username')
mycursor.execute('SELECT * FROM userpass WHERE username = username')
results = mycursor.fetchall()



if results:
    print('Username is taken')
else:
    print('did not work')`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    相关资源
    最近更新 更多