【问题标题】:SQLite3 - Preventing duplicate entries from being entered into a databaseSQLite3 - 防止重复条目被输入数据库
【发布时间】:2017-02-22 10:03:10
【问题描述】:

首先,在我提出的问题太初级时提前道歉 - 我是一个 SQLite 新手,刚刚开始接触并尝试使用 Python 和 SQLite3 完成一项简单的任务。

我有一个带有两个文本字段的 SQLite 数据库文件 (notify_users):language_codeusername。我正在使用此执行代码将信息输入数据库,例如:cursor.execute("INSERT INTO notify_users VALUES ('de', 'jane_doe')"):

可视化的话,数据库是这样的:

| language_code | username      |
---------------------------------
| de            | jane_doe      |
| sv            | jane_doe      |
| de            | tom_petty     |

等等。虽然可以将一个用户名与多个语言代码相关联,但我想防止重复条目同时使用相同的语言代码和用户名

如果INSERT INTO 代码在两个字段中与已经存在的字段完全相同,我应该如何更改它不会创建一个新条目?

| language_code | username      |
---------------------------------
| de            | jane_doe      |
| de            | jane_doe      | X # Don't want this duplicate entry to be entered. 

谢谢,如果我能做些什么来更准确或更具体地解决这个问题,请告诉我。

【问题讨论】:

    标签: python database python-3.x sqlite


    【解决方案1】:

    让数据库完成工作。创建唯一索引。这将防止此类重复:

    create unique index unq_notify_users_2 on notify_users(language_code, username);
    

    它通过生成错误来防止重复。虽然最好在数据库中进行检查,但您可以通过执行以下操作来避免错误:

    insert into notify_users(language_code, username)
        select language_code, username
        from (select $language_code as language_code, $username as username) lu
        where not exists (select 1
                          from notify_users nu
                          where nu.language_code = lu.language_code and
                                nu.username = lu.username
                         );
    

    【讨论】:

    • 谢谢,戈登 - 这是我运行的单独命令吗? (原谅我的无知!)
    • @JohnSmith 。 . . create index 是您在数据库中执行的操作,一次。 insert 是如何插入数据的示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 2016-07-23
    • 1970-01-01
    • 2012-08-02
    • 2017-08-14
    相关资源
    最近更新 更多