代码之家  ›  专栏  ›  技术社区  ›  Jaromír StaÅ¡

如果用户名已存在,则从数据库中获取正确或错误的返回值

  •  -4
  • Jaromír StaÅ¡  · 技术社区  · 1 年前

    我正在制作一个使用数据库的小项目,当用户创建帐户时,我需要检查数据库中的用户名是否可用。

    我的代码是这样的:

    db = mysql.connector.connect(
        host="localhost",
        user="user",
        password="password",
        database = "users"
    
    mycursor = db.cursor()
    
    
    username = input("Username: ")
    
    mycursor.execute("SELECT username FROM users")
    
    for x in mycursor:
        if x == username:
            print(True)
        else:
            print(False)
    

    我看到了一些类似的问题,但它们要么与Python无关,要么对我不起作用,要么我就是不理解它们。

    1 回复  |  直到 1 年前
        1
  •  1
  •   oskar    1 年前
    import mysql.connector
        
    # Connect to the database
    db = mysql.connector.connect(
        host = "localhost",
        user = "user",
        password = "password",
        database = "users",
    )
    
    mycursor = db.cursor()
    username = input("Username: ")
    
    # Use SELECT and WHERE to check if it already exists
    query = "SELECT username FROM users WHERE username = %s"
    mycursor.execute(query, (username,))
    
    # Fetch one result
    result = mycursor.fetchone()
    
    # Check if the result is None or not
    if result:
        print(True)  # Username exists
    else:
        print(False)  # Username does not exist
    
    mycursor.close()
    db.close()