【问题标题】:How can I check if a record exists for a given username in this table?如何检查此表中给定用户名的记录是否存在?
【发布时间】:2019-07-17 18:46:02
【问题描述】:

如何检查是否存在记录的用户名具有变量 usernameentryentry 的值的记录?

我想创建一个 if 语句,这样如果已经有一条用户名与 usernameentryentry 变量值相同的记录,那么用户就会被告知该用户名已被使用。

我该怎么做?

import sqlite3

with sqlite3.connect("userdatabase.db") as db: 
    cursor = db.cursor() 

usernameentryentry = "username1"

cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
userID INTEGER PRIMARY KEY,
username VARCHAR(20) NOT NULL, 
password VARCHAR(20) NOT NULL) ;
''') 

#variable defined below for use in the if statement:
#variable = true if there isnt a record with the username "username1" and 
#false if there is a record with the username "username1"

【问题讨论】:

  • 对 SQL 中的 WHERE 子句进行谷歌搜索。然后,试一试,如果您遇到困难,人们会帮助您。
  • 我使用了代码: cursor.execute('''SELECT username, password FROM users WHERE username=?''', [usernameentry]) userdetails = cursor.fetchone() 。当我在没有记录的情况下打印 userdetails 时,它会打印“None”,但如果我对 if userdetails = “None”使用 if 语句,则执行此命令,当没有记录且 userdetails 应等于“None”时,该命令不是执行

标签: python sql sqlite


【解决方案1】:

This post 展示了如何以优化的方式检查记录是否存在

检查 usernameentryentry 是否已经被占用:

cursor.execute('''SELECT 1 FROM users WHERE username = (?)''',[usernameentryentry])

如果没有记录,“cursor.fetchone()”的值为“None”。您可以在条件表达式中使用它(None 的值为 false)。

所以你的代码应该是这样的:

def insertUser(userID, usernameentryentry, password):
    cursor.execute('''SELECT 1 FROM users WHERE username = (?)''',[usernameentryentry])
    userAlreadyExists = cursor.fetchone()
    if(userAlreadyExists):
        print("Username already exists")
    else:
        cursor.execute('''INSERT INTO users(userID, username, password) VALUES(?,?,?)''', (userID,usernameentryentry,password))
        db.commit()

您可以尝试插入用户两次并自己检查:

insertUser(123,'james','pwd123')
insertUser(124,'james','blink182')

查看所有用户:

cursor.execute('''SELECT * FROM users''')
result = cursor.fetchall()
print(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多