问题描述
每次运行这段代码,我插入表中的数据都是重复的,那么如何防止重复呢?
我试图寻找解决方案,但徒劳无功。我尝试在 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()
解决方法
在您的表中创建一个主键,并在该约束上设置冲突,如下所示:
create table if not exists users
(
user_id integer primary key not null on conflict ignore,name text,age integer,phone integer
)
现在如果主键被破坏,当你插入或更新时什么也不会发生。 另外,以 int 数据类型保存电话号码的快速提示不是最佳做法,它需要更多内存,而且您只能使用数字等。
,您正在检查表是否存在以创建表。但是以任何方式插入行。请将第二行更改如下,首先检查用户表是否已经有 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)")