0

I am trying to check if a row exist in an sqlite3 table in python. i want to check if there is an existing username in the table. my function is a class method here is my code method.

def usercheck(self,username):
    conn=sqlite3.connect(self.db)
    c=conn.cursor()
    try :
        user=c.execute("SELECT True FROM Users  WHERE Username= %s " %(username)).fetchone()
        if user != None:
            return True
        else :
            return False

    except sqlite3.OperationalError as e:
        print(' AN ERROR OCCURED')
        raise 
    conn.close() 

usercheck('admin')

But i get an error saying no such column

 user=c.execute("SELECT True FROM Users  WHERE Username= %s " %(username)).fetchone()
 sqlite3.OperationalError: no such column: admin

I have aslo tried it this way

user=c.execute("SELECT True FROM Users  WHERE Username= ? " (username)).fetchone()
        

I got a differet error code

TypeError: 'str' object is not callable
Adétóbi
  • 1
  • 1
  • You're using string interpolation rather than binding your username, meaning that it's being interpreted as a column; you need to use [bind variables](https://stackoverflow.com/questions/14949833/searching-sqlite-database-with-python-variables). When in this situation always look at the actual SQL being executed, and the issue often becomes much clearer. – Ben Apr 30 '22 at 12:10
  • i have also tried it this way and it give an error too. TypeError: 'str' object is not callable – Adétóbi Apr 30 '22 at 12:16
  • `user=c.execute("select 1 from users where username = ?", username).fetchone()`. You're missing a comma, leading to `(username)` being interpreted as a method – Ben Apr 30 '22 at 12:24
  • it gives this error ''' sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 5 supplied. ''' – Adétóbi Apr 30 '22 at 12:29
  • 'user=c.execute("SELECT 1 FROM Users WHERE Username= ? " ,(username,)).fetchone()' . i finally did it. I made the username become seem like a tuple by adding a ',' after it inside the pareenthesis – Adétóbi Apr 30 '22 at 12:38

1 Answers1

0

Try this

user=c.execute("SELECT True FROM Users  WHERE Username= %s ",(username,)).fetchone()