首页 > 解决方案 > 如何使用 Python 防止 SQLite 中的重复行或数据?

问题描述

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

我试图寻找解决方案,但徒劳无功。我尝试在INSERT INTO中使用“如果不存在”作为“如果不存在用户则插入”,但是数据的重复仍然存在并且它不起作用。

我发现一个错误说: 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()

标签: pythonsqlsqlitesql-insertnot-exists

解决方案


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

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

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


推荐阅读