[英]Python cx_Oracle executemany() function how to handle exception if one of the records fail?
[英]How to handle exception with executemany (MySQL and Python)
我有一個使用 executemany 將行批量插入 MySQL 表的 python 腳本。 數據是從不同的 API 檢索的,因此時不時會有意外數據導致一行導致異常。
如果我理解正確 - 當調用具有 1,000 行的 executemany 並且其中一個有問題時 - 不會插入整個批量。
我想找到一種提交1000條記錄並成功加載沒有問題的記錄的方法。 因此,例如 - 如果一千個中的一個有問題,它將不會被加載,但所有其他 999 將被加載。
最好的做法是什么? 我正在考慮捕獲一個異常並創建一個后備以重新提交所有 1000 個 - 但似乎必須有更好的方法來實現相同的結果。
建議?
在“executemany”查詢的開頭執行“INSERT OR IGNORE”語句將使您完全做到這一點 - 它只會添加不會帶來錯誤的值。
唯一的缺點是您無法再看到發生了什么錯誤。 例如,
原始數據庫:
('kaushik', 3)
('maria', 4)
('shreya', 38)
查詢:(在python中)
listofnames = [
('kaushik', 3),
('maria', 4),
('jane', 56)
]
c.executemany("INSERT OR IGNORE INTO bob (name, number) VALUES (?,?)",
listofnames)
最終數據庫:
('kaushik', 3)
('maria', 4)
('shreya', 38)
('jane', 56)
插入時, executemany
將所有數據行批處理在一起,並嘗試使用一個命令將它們全部插入。 據我所知,沒有辦法在不破壞整批插入的情況下處理一次失敗插入引發的異常。 如果一行失敗,則整個命令都會失敗。
這是它的樣子(示例取自MySQL 文檔)。 如果你告訴它這樣做:
data = [
('Jane', date(2005, 2, 12)),
('Joe', date(2006, 5, 23)),
('John', date(2010, 10, 3)),
]
stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s)"
cursor.executemany(stmt, data)
executemany
會這樣做:
INSERT INTO employees (first_name, hire_date)
VALUES ('Jane', '2005-02-12'), ('Joe', '2006-05-23'), ('John', '2010-10-03')
如果您認為這種情況很少發生,那么您單獨重試每個插入的想法會奏效。 就像是:
try:
cursor.executemany(stmt, data)
except ___Error: # fill in the blank
for datum in data:
try:
cursor.execute(stmt, datum)
except ___Error:
# handle exception, eg print warning
...
如果您認為這將是一個常見問題,那么放棄executemany
並執行以下操作可能會更executemany
:
for datum in data:
try:
cursor.execute(stmt, datum)
except ___Error:
# handle exception, eg print warning
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.