python SQLite ->检查用户名是否已经存在

qxsslcnc  于 2023-01-29  发布在  Python
关注(0)|答案(3)|浏览(183)

当用户创建一个帐户时,需要检查用户名是否已经存在于SQLite数据库中。此函数的任务是检查这一点,并且当前接受用户输入的用户名。但是,无论何时运行此程序,当输入不存在的用户名时,它不会返回True,因此由于此问题,无法创建新帐户。如果用户输入的用户名在表中不存在,我需要返回true。
这是我目前拥有的

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
szqfcxe2

szqfcxe21#

问题是checkDB()函数未正确检查SQLite数据库以查看用户输入的用户名是否已存在。即使输入了不存在的用户名,函数也仅返回False。这意味着无法创建新帐户。要解决此问题,已更新函数,以便在新用户名不存在时也将其插入数据库。如果用户名不存在,则允许返回True。

我相信这会奏效:

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
bihw5rsg

bihw5rsg2#

您可以利用None是falsy这一事实来检查用户是否存在。
首先,为什么不为用户名使用占位符?,然后您使用了比必要的查询更复杂的查询。

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()

如果需要,也可以作为函数,显式检查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

注意我传递了一个游标作为函数参数,这是为了依赖反转。

nbnkbykc

nbnkbykc3#

经过反复,我能够拿出一个解决方案,在这里,它是在情况下,任何人都有一个类似的问题,在自己的程序

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

相关问题