Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting a true or false return from database if a username already exists

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()**
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading