python - 如何使用 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()
解决方案
在您的表中创建一个主键并在该约束上设置冲突,如下所示:
create table if not exists users
(
user_id integer primary key not null on conflict ignore
, name text
, age integer
, phone integer
)
现在,如果违反了该主键,那么当您插入或更新时,什么也不会发生。快速提示以 int 数据类型保存电话号码不是最佳做法,它需要更多内存,并且您仅限于数字等。
推荐阅读
- c# - 如何动态解析数据列表并在树视图中显示结果
- algorithm - 如何阅读这个最长递增的子序列递归关系
- r - 如何修复 R markdown 中的 Kable 表错误?
- javascript - Vue v-for 循环“项目”未定义
- python - 你如何列出 Python 中的所有警告过滤器?
- dataframe - 数据框所有列的转换函数
- google-sheets - Col BY 在 Google 表格查询中导致解析错误
- node.js - 如何从 pubsub.schedule 调用 http 函数
- python - 如何修改 Scipy 的 SVM 分类规则?
- python - 递归期间变量变化的状态