如何用Python创建含单条记录的SQLite3数据库且避免重复创建
解决Python创建SQLite单条记录不重复插入的问题
Got it, let's fix this for you. The issue with your current code is that the if True condition will always trigger the INSERT, which is why you're getting duplicate records every time you run the script. Here are two reliable approaches to ensure only one instance of your target record exists in the database:
方法1:先查询再插入(无需修改表结构)
这种方法先检查目标记录是否已经存在,只有当它不存在时才执行插入操作,逻辑直观且不需要调整表的约束:
import sqlite3 # 定义要插入的固定记录数据 no1 = "Null" no2 = "Null" no3 = "Null" value = 1 # 使用上下文管理器自动管理连接和事务 with sqlite3.connect('db_M.db') as conn: cursor = conn.cursor() # 确保表存在(不存在则创建) cursor.execute(""" CREATE TABLE IF NOT EXISTS M_Memory( Name TEXT, Person TEXT, memory TEXT, value REAL ) """) # 查询是否存在匹配的记录 cursor.execute(""" SELECT COUNT(*) FROM M_Memory WHERE Name = ? AND Person = ? AND memory = ? AND value = ? """, (no1, no2, no3, value)) # 获取查询结果:fetchone()[0]返回匹配的记录数 record_exists = cursor.fetchone()[0] > 0 if not record_exists: # 插入新记录 cursor.execute(""" INSERT INTO M_Memory(Name, Person, memory, value) VALUES (?, ?, ?, ?) """, (no1, no2, no3, value)) print("新记录已成功插入") else: print("记录已存在,无需重复插入")
方法2:使用INSERT OR IGNORE + 唯一约束(更简洁高效)
如果希望依赖数据库的约束来避免重复,可以给表添加唯一约束,然后用INSERT OR IGNORE语句——当插入的记录违反唯一约束时,数据库会自动忽略这次插入操作:
第一步:创建带唯一约束的表
import sqlite3 with sqlite3.connect('db_M.db') as conn: cursor = conn.cursor() # 创建表时,给需要唯一标识的字段组合添加UNIQUE约束 cursor.execute(""" CREATE TABLE IF NOT EXISTS M_Memory( Name TEXT, Person TEXT, memory TEXT, value REAL, UNIQUE(Name, Person, memory, value) ) """)
第二步:插入记录(自动忽略重复)
之后每次执行插入时,直接用INSERT OR IGNORE即可,无需提前查询:
import sqlite3 no1 = "Null" no2 = "Null" no3 = "Null" value = 1 with sqlite3.connect('db_M.db') as conn: cursor = conn.cursor() # 插入记录,重复时自动忽略 cursor.execute(""" INSERT OR IGNORE INTO M_Memory(Name, Person, memory, value) VALUES (?, ?, ?, ?) """, (no1, no2, no3, value)) # 检查是否有记录被插入(rowcount返回受影响的行数) if cursor.rowcount > 0: print("新记录已插入") else: print("记录已存在,未执行插入")
两种方法对比
- 方法1:无需修改表结构,逻辑清晰,适合不需要严格约束的场景。
- 方法2:代码更简洁,依赖数据库层面的约束,效率更高,适合需要确保记录唯一性的场景。
内容的提问来源于stack exchange,提问作者Ali.M.Kamel
相关产品推荐
相关产品推荐

