I am making a small project that uses a database, when user is creating an account, I need to check the database if the username is available.
My code is something like this:
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)
I saw some similar questions to this, but they either aren’t with Python, they aren’t working for me or I just don’t understand them.
>Solution :
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"strong text
mycursor.execute(query, (username,))
#Fetch one resutl
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()**