-1

Hi having some issues with SQLite3 been having a good time with it up until now but recently ran into some issues when I was trying to check if a select statement looking at all the usernames in the database is fault such that there is no user with that username already to add the newly registered user to the database I'd really appreciate some help the code is below

if form.validate_on_submit():
    email = form.email.data
    username = form.username.data
    password = form.password.data
    hashedpassword = sha256_crypt.hash(password)
    print(email, username, hashedpassword)
    db = get_db()
    if not db.execute(f'SELECT * FROM USERS WHERE "{username}" == USERNAME'):
        cursor = db.execute(
        f'INSERT INTO USERS(USERNAME, USERPASSWORD, USEREMAIL) VALUES(?,?,?)', (username, hashedpassword, email)
        )
        db.commit() 
  • If `db` here is actually a Cursor instance, then `execute` is https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute ... it's not clear what this method returns, I would have guess maybe `None` but if you say its not falsy then maybe it returns the Cursor object again. To check the results you need to follow it with something like `db.fetchall()`. But if you don't care about the user rows I suggest write the query as `SELECT count(*) FROM...` and check the number returned, it will be more efficient – Anentropic May 13 '22 at 16:49
  • I wrote this answer here https://stackoverflow.com/a/71153199/3155240 that might be of some help. There is usually a fetchall statement and you'll have to iterate through those. You can also just check for a `len()` of 0. – Shmack May 13 '22 at 17:24
  • You can use something like `db.execute(f'SELECT COUNT(*) FROM USERS WHERE USERNAME == ?;', (username,)).fetchone()[0] == 0` to prevent an iterate, and also prevent the SQL Injection attack possibility. – Anon Coward May 13 '22 at 18:03

0 Answers0