首页 > 解决方案 > 如何在 Sqlite Python 中检查重复数据?

问题描述

我有这段代码可以从 tkinter python 的输入字段中获取电子邮件并将其存储在数据库中,我稍后计划使用这些数据将电子邮件自动发送到数据库中的所有电子邮件。但唯一的问题是,如果我两次输入相同的电子邮件,它会将它们保存在数据库中而没有错误,这将导致向电子邮件发送重复的信息。那么任何人都可以建议我应该采取什么方法吗?

def submit():
# Creates the connection from the database.py
conn = sqlite3.connect("email.db")
c = conn.cursor()

# Insert into the database table
c.execute(
    "INSERT INTO email VALUES (:email_address)", {"email_address": user_email.get()}
)

conn.commit()
conn.close()

# Clear The Text Boxes
user_email.delete(0, END)

这就是我从数据库中检索信息的方式,如果它有用的话

def emailGet():
# Creates the connection from the database.py
conn = sqlite3.connect("email.db")
c = conn.cursor()

c.execute("SELECT *, oid FROM email")
records = c.fetchall()
print("This is all the emails in the database : " + str(records))
global get_records
global new_record
get_records = ""

for i in records:
    get_records += str(i[0] + ",")
    #print(get_records)
    new_record = get_records[:-1]
    print(new_record)

conn.commit()
conn.close()

标签: pythonsqlite

解决方案


您可以使用SELECT语句来检查您从条目中获取的电子邮件是否在数据库中。像这样的东西:

def checkEmailExistance():
    email_exists = False
    c.execute('SELECT * FROM email WHERE <email adresses column> = :email_adress'
    {"email_address": user_email.get()})

    # Previous line selects a row of your database only if the column that contains
    # the email adress in said row has the same adress as the one from the entry

    if c.fetchone() # which is the same as saying "if c.fetchone retrieved something in it"
        email_exists = True 
    else:
        email_exists = False
    return email_exists

此外,不是使用email_exists变量,您可以只返回 True 或 False 来缩短代码,我以这种方式编写它是为了便于阅读。

编辑这与您的问题无关,但是在使用数据库时,我发现在每个自动加载和更新的表的开头添加“value_id”列非常有用,您永远不知道何时需要它!

希望这可以帮助


推荐阅读