Skip to content Skip to sidebar Skip to footer

How Do I Make Sql Python Find If A Username Is Already In The Database?

This is my first time using SQL and I am very confused. I want python to check if a username is already in the database. For example, someone writes 'register' it will take their u

Solution 1:

mycursor.execute by itself only prepares and executes the query, but it will not give you the result.

To get the result, you'll have to use one of the cursor's fetch methods, such as fetchone(), fetchmany(), or fetchall().

Example:

mycursor.execute("""SELECT * FROM TestDatabase WHERE name=%s""", (Username,))
rows = mycursor.fetchall()

Then you can check rows afterwards.

You can find more information on the cursor methods here:

https://www.python.org/dev/peps/pep-0249/

Follow-up:

Note that the parameters must be an iterable, e.g. a tuple or a list, even if you're only passing one parameter to the cursor.

This will fail:

mycursor.execute("""SELECT * FROM TestDatabase WHERE name=%s""", (Username))

To make it a tuple add a , after Username:

mycursor.execute("""SELECT * FROM TestDatabase WHERE name=%s""", (Username,))

or make it a list:

mycursor.execute("""SELECT * FROM TestDatabase WHERE name=%s""", [Username])

Post a Comment for "How Do I Make Sql Python Find If A Username Is Already In The Database?"