【问题标题】:How to tell if a value exists in a sqlite3 database, python [duplicate]如何判断sqlite3数据库中是否存在值,python [重复]
【发布时间】:2018-01-16 02:01:02
【问题描述】:

如何判断一个值是否存在于 sqlite3 数据库中,python

到目前为止,这是我的代码:

def signup():
    email = request.form['email']
    username = request.form['user']
    password = request.form['password']
    g.db.execute("INSERT INTO users VALUES (?, ?, ?)", [email, username, password])
    g.db.commit()

如果emailusername 不在数据库中,我希望它只将值插入数据库,但我不知道从哪里开始。

【问题讨论】:

    标签: python sqlite


    【解决方案1】:

    您所要做的就是在插入之前进行查询,然后执行fetchone。如果fetchone 返回一些东西,那么您肯定知道数据库中已经有一条记录具有emailusername

    def signup():
        email = request.form['email']
        username = request.form['user']
        password = request.form['password']
    
        # Create cursor object
        cur = g.db.cursor()
    
        # run a select query against the table to see if any record exists
        # that has the email or username
        cur.execute("""SELECT email
                              ,username
                       FROM users
                       WHERE email=?
                           OR username=?""",
                    (email, username))
    
        # Fetch one result from the query because it
        # doesn't matter how many records are returned.
        # If it returns just one result, then you know
        # that a record already exists in the table.
        # If no results are pulled from the query, then
        # fetchone will return None.
        result = cur.fetchone()
    
        if result:
            # Record already exists
            # Do something that tells the user that email/user handle already exists
        else:
            cur.execute("INSERT INTO users VALUES (?, ?, ?)", (email, username, password))
            g.db.commit()
    

    【讨论】:

    • @Daniel 然后我会修改为:SELECT email, username FROM users WHERE email=? or username=?。您指定了“emailusername”,所以我假设您想要同时进行这两项检查。我会更改我的答案。
    • @Adonis 是的,但我想应用程序会通知用户是否存在记录
    • @Daniel“选择电子邮件,用户名...”,而不是“选择,电子邮件用户名”:P
    • @Daniel 我已包含 cmets 并将我的解决方案包装在您的函数中。希望对您有所帮助!
    • @Daniel 啊,所以您的 g.db 对象不是光标对象。您应该在使用execute 方法之前创建一个游标对象。那我会编辑我的答案。
    猜你喜欢
    • 1970-01-01
    • 2012-10-07
    • 2016-08-19
    • 2015-06-11
    • 1970-01-01
    • 2013-05-12
    • 2020-07-18
    • 2014-10-10
    • 1970-01-01
    相关资源
    最近更新 更多