我的数据库的设计如下。
combinations_sql = """
CREATE TABLE IF NOT EXISTS combinations
(id integer PRIMARY KEY,
city text NOT NULL,
industry text NOT NULL,
round text,
result int,
CONSTRAINT unq UNIQUE (city, industry, round)
)
"""
城市、行业、回合的组合是独一无二的,当我需要添加新数据时,我想检查数据是否已经存在于我的数据库中
到目前为止,我使用 INSERT 或 IGNORE
combinations_sql = """
INSERT OR IGNORE INTO combinations (city, industry, round, result) VALUES (?,?,?,?)
"""
但我不确定这种方法的正确性。当我添加新参数时,它们仍然出现在 db 中,尽管它们不应该出现。
编辑:我解决了问题但性能更差的解决方法:
combinations_sql = """
SELECT * FROM combinations WHERE city = ? AND industry = ?
"""
cursor.execute(combinations_sql, (city,industry))
entry = cursor.fetchone()
if entry is None:
combinations_sql = """
INSERT INTO combinations (city, industry , round, result) VALUES (?,?,?, ?)
"""
cursor.execute(combinations_sql, (city, industry, round, result))
print("Entry added")
else:
print("Entry found")