SQLite3 Python - Checking if an entry exists

Viewed 3396

I'm trying to check for duplicate usernames in a database but I'm getting the error:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied.

What are the bindings referred to here and how might I go about fixing this?

conn = sqlite3.connect('data.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS users (username, f_name, l_name, age, email, uid)''')
for u in range(0,1):
   a1 = input("Enter desired username:\t")
   a2 = input("Enter first name:\t")
   a3 = input("Enter last name:\t")
   a4 = input("Enter age:\t")
   a5 = input("Enter email:\t")
   a6 = str(uuid4())
   add = [a1,a2,a3,a4,a5,a6]
   c.execute('''SELECT username FROM users WHERE username=?''', a1)
   exists = c.fetchall()
   if not exists:
       c.execute('INSERT INTO users VALUES(?,?,?,?,?,?)',add)
       conn.commit()
   else:
       print("Error: Username already in use.\n")
1 Answers

There's a subtle problem in this line:

c.execute('''SELECT username FROM users WHERE username=?''', a1)

The second argument to .execute() must be a container!
So you can do something like this instead and it will work:

c.execute('''SELECT username FROM users WHERE username=?''', (a1,))
                                                           # ^  ^^ this is now a tuple!
Related