简体   繁体   中英

SQLite -> Checking if a username already exists

When a user creates an account it needs to check whether the username already exists within the SQLite database. This functions job is to check this and currently takes in the username that the user has inputted. However, whenever running this it wouldn't return True when a username that doesn't exist is inputted so a new account can never be created due to this issue. I need this to return true if the username that the user has inputted doesn't already exist in the table.

This is what I currently have

def checkDB(username):
    c.execute('select exists(select 1 from LoginCredentials where username = [username])')
    [exists] = c.fetchone() # fetch and unpack the only row our query returns
    if exists:
        print("False")
        return False # Returns false if the username already exists in the database
    else:
        print("True")
        return True # Returns true if the username doesn't exist in the database

You can use the fact that None is falsy to check the existence of a user.

First thing why are you not using a placeholder ? for the username, then you've used a more complex than necessary query.

import sqlite3

con = sqlite3.connect(":memory:")

cur = con.cursor()

cur.execute("CREATE TABLE LoginCredentials (username VARCHAR)")
cur.execute("INSERT INTO LoginCredentials VALUES ('ljmc')")

cur.execute("SELECT 1 FROM LoginCredentials WHERE username = ?", ("ljmc",))

if cur.fetchone():  # (1,) is returned as one row matched, non empty tuple is truthy
    print("ljmc exists")  # will print

cur.execute("SELECT 1 FROM LoginCredentials WHERE username = ?", ("nonexistent",))

if cur.fetchone():  # None is returned as no row matched, None is falsy
    print("nonexistent exists")  # won't print

con.close()

Or as a function if you want, with explicitly checking for None.

def user_exists(cur: sqlite3.Cursor, username: str) -> bool:
    cur.execute("SELECT 1 FROM LoginCredentials WHERE username = ?", (username,))
    return cur.fetchone() is not None

Notice I pass a cursor as a function argument, this is for dependency inversion.

The problem was that the checkDB() function was not correctly checking the SQLite database to see if the username entered by the user already existed. The function was only returning False, even when a username that didn't exist was inputted. This meant that a new account could not be created. To fix this issue, the function was updated to also insert the new username to the database if it did not already exist, which then allowed it to return True if the username did not already exist.

I believe this will do the trick:

def checkDB(username):
    c.execute('select exists(select 1 from LoginCredentials where username = [username])')
    [exists] = c.fetchone() # fetch and unpack the only row our query returns
    if exists:
        print("False")
        return False # Returns false if the username already exists in the database
    else:
        print("True")
        c.execute('''INSERT INTO LoginCredentials(username) VALUES(?)''', (username,)) // Inserts the new username to the database
        conn.commit()
        return True # Returns true if the username doesn't exist in the database

After going back and forth I was able to come up with a solution here it is in case anybody else is having a similar issue in their own program

    def checkDB(username):
    c.execute("SELECT username FROM LoginCredentials")
    query = c.fetchall()
    length = len(query)
    for i in range(length):
        dbUsername = query[i][0]
        if username == dbUsername:
            return True
    return False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM