【问题标题】:How to prevent duplicate rows or data in SQLite with Python?如何使用 Python 防止 SQLite 中的重复行或数据?
【发布时间】:2021-07-23 21:23:22
【问题描述】:

每次运行这段代码,我插入表中的数据都是重复的,那么如何防止重复呢?

我试图寻找解决方案但徒劳无功。我尝试在 INSERT INTO 中使用“if not exists”作为“INSERTO INTO if not exists users”,但数据重复仍然存在并且不起作用。

我发现一个错误提示:sqlite3.OperationalError: near "not": syntax error

这是代码:

import sqlite3

db = sqlite3.connect('data.db')

cr = db.cursor()

cr.execute("CREATE TABLE if not exists users (user_id INTEGER, name TEXT, age 
INTEGER, phone INTEGER)")

cr.execute("INSERT INTO if not exists users (user_id, name, age, phone) 
VALUES(1, 'Ahmed', 33, 01001234567)")

cr.execute("SELECT * FROM users")

 user = cr.fetchall()
 print(user)
 db.commit()

【问题讨论】:

  • 以文本格式粘贴代码而不是屏幕截图
  • 每次运行此代码时,都会再次插入同一行。你有什么问题?
  • 这是代码:import sqlite3 db = sqlite3.connect('data.db') cr = db.cursor() # Create DB table of User cr.execute("CREATE TABLE if not exists users (user_id INTEGER, name TEXT, age INTEGER, phone INTEGER)") cr.execute("INSERT INTO if not exists users (user_id, name, age, phone) VALUES(1, 'Ahmed', 33, 01001234567)") cr.execute("SELECT * FROM users") user = cr.fetchall() print(user) db.commit()
  • if not exists 什么? user_id? name?两个都?编辑您的问题并澄清。

标签: python sql sqlite sql-insert not-exists


【解决方案1】:

在您的表中创建一个主键并设置该约束的冲突,如下所示:

create table if not exists users
( 
  user_id integer primary key not null on conflict ignore 
  , name text 
  , age integer 
  , phone integer
)

现在,如果违反了该主键,那么当您插入或更新时,什么也不会发生。 还快速提示以 int 数据类型保存电话号码不是最佳做法,它会占用更多内存,并且您仅限于数字等。

【讨论】:

    【解决方案2】:

    您正在检查表是否存在以创建表。但是以任何方式插入行。请更改下面的第二行,首先检查 users 表是否已经有 user_id 为 1 的数据。

    cr.execute("insert into users (user_id,name,age,phone) Select 1,'Ahmed',33,01001234567 where not exists (select 1 from users where user_id=1)")
    

    【讨论】:

      猜你喜欢
      • 2018-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 2010-11-09
      • 2012-01-21
      • 2016-07-23
      • 1970-01-01
      相关资源
      最近更新 更多