【问题标题】:SQLite : Return true if duplicate values are found in tableSQLite:如果在表中找到重复值,则返回 true
【发布时间】:2022-01-25 03:42:35
【问题描述】:

我想知道如何在表中找到重复值并使其返回 True。我看到了很多关于这个的问题,但没有一个有帮助,谢谢!

这是我的例子:

import hashlib
import sqlite3

con = sqlite3.connect('users/accounts.db')
cur = con.cursor()
info = cur.execute("SELECT * FROM accounts;").fetchall()

print("Sign Up.")
username = input("Input your username : ")
password = input("Input your password : ")
email = input("Input your email: ")

result = hashlib.sha256(password.encode("utf-8"))
result_2 = str(result.digest)

cur.execute("insert into accounts (username, password, email) values(?,?,?)", (username, result_2, email))

con.commit()
print(info)
con.close()

免责声明

对于那些想知道的人,不,这不会在生产环境中使用,它不安全并且很容易被利用。甚至还没有加盐。

【问题讨论】:

  • 您能否添加示例数据来解释您的问题?
  • 添加了@TimBiegeleisen
  • 使用示例数据和预期结果编辑您的问题,以澄清您的问题。

标签: python sqlite sql-insert


【解决方案1】:

如果您的目标是防止插入带有其他人已使用的用户名或电子邮件的新用户记录,那么存在查询提供了一个选项:

INSERT INTO accounts (username, password, email)
SELECT ?, ?, ?
WHERE NOT EXISTS (SELECT 1 FROM accounts WHERE username = ? OR email = ?);

也就是说,在单个语句中,我们还可以检查提供的用户名或电子邮件是否已经出现在 accounts 表中的某个位置。

更新的 Python 代码:

sql = """
    INSERT INTO accounts (username, password, email)
    SELECT ?, ?, ?
    WHERE NOT EXISTS (SELECT 1 FROM accounts WHERE username = ? OR email = ?)
"""
cur.execute(sql, (username, result_2, email, username, email))

【讨论】:

    【解决方案2】:

    假设你有这张桌子:

    create table foo (
       foo_id numeric(12,0) primary key,
       str_value varchar(200)
    );
    

    并且您想查找 str_value 的重复值。

    你可以这样做:

    select str_value
      from foo
     group by str_value
    having count(1) > 1;
    

    您将有一个 str_values 列表,上面有重复。

    如果您想知道每个 str_value 有多少重复项,您可以将 count(1) 添加到您的 select 子句中:

    select str_value, count(1)
      from foo
     group by str_value
    having count(1) > 1;
    

    【讨论】:

    • 是的,但是如果发现重复项,我如何返回 True @Pablo Santa Cruz
    【解决方案3】:

    所以这段代码起作用了

    b = cur.execute("select * from accounts").fetchall()
    
    sql = """INSERT INTO accounts (username, password, email)
             SELECT ?, ?, ?
             WHERE NOT EXISTS (SELECT 1 FROM accounts WHERE username = ? OR email = ?)"""
    cur.execute(sql, (username, str(result.digest()), email, username, email))
    
    a = cur.execute("select * from accounts").fetchall()
    
    if a > b:
        print("Registration Complete.")
    else:
        print("Failed : Username or Email already exists.")
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 2015-08-10
    • 2017-03-11
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多