我的数据库的设计如下。
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")