我有一個現有的 Sqlite 表,其中包含學生的資格資料,代碼會定期檢查獲得的新資格并將它們插入表中。這會導致重復。
def insertQualificationData(data):
# Run execute many command to insert data
self.cursor.executemany(
"""
INSERT INTO qualification (
qualificationperson,
type,
secondaryreference,
reference,
name,
pass,
start,
qualificationband,
grade,
time_stamp
) VALUES (?,?,?,?,?,?,?,?,?,?)
""", data
)
'data' 變數是一個元組串列。例如:
('209000010111327', 'WLC', 'G0W915', 'Certificate', 'Child Care and Education', 'P', '12/07/2001', 'PASS', 'Pass', 1648018935)
我想防止將“重復”值插入到資格表中,“重復”是指如果一行與不應插入的資格人員、參考、名稱和通過列匹配。
我已經看到其他答案在做類似的事情,但是使用第二個表中的命名列,我正在努力使用元組串列和 executemany() 來復制它
uj5u.com熱心網友回復:
您可以在這些列上添加唯一索引:
CREATE UNIQUE INDEX IF NOT EXISTS QData ON qualification (qualificationperson, reference, name, pass)
然后使用一條INSERT OR IGNORE陳述句,以便插入一個值的失敗不會導致整個executemany失敗:
INSERT OR IGNORE INTO qualification (...)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/451674.html
下一篇:如何計算sql中的范圍?
