[英]How do I check if an insert was successful with MySQLdb in Python?
我有這個代碼:
cursor = conn.cursor()
cursor.execute(("insert into new_files (videos_id, filename, "
"is_processing) values (%s,%s,1)"), (id, filename))
logging.warn("%d", cursor.rowcount)
if (cursor.rowcount == 1):
logging.info("inserted values %d, %s", id, filename)
else:
logging.warn("failed to insert values %d, %s", id, filename)
cursor.close()
有趣的是, cursor.rowcount
總是一個,即使我更新了我的數據庫,使videos_id成為一個唯一的密鑰。 也就是說,插入失敗,因為在我的測試中會出現相同的videos_id
(當我檢查數據庫時,沒有插入任何內容)。 但無論出於何種原因, rowcount
總是為1 - 甚至是logging.warn
我吐出的行rowcount
為1。
那么,問題是:
如果插入正常,我可以使用rowcount
出來嗎? 如果是這樣,我(大概)做錯了什么? 否則,我如何檢查插入是否正常?
修改后您的代碼不會提交(您的修改將被回滾)。 那就是你應該在cursor.execute
之后添加以下行:
conn.commit()
插入失敗將拋出MySQLdb.IntegrityError
,因此您應該准備好捕獲它。
因此,您的代碼應該類似於:
sql_insert = """insert into new_files (videos_id, filename, is_processing)
values (%s,%s,1)"""
cursor = conn.cursor()
try:
affected_count = cursor.execute(sql_insert, (id, filename))
conn.commit()
logging.warn("%d", affected_count)
logging.info("inserted values %d, %s", id, filename)
except MySQLdb.IntegrityError:
logging.warn("failed to insert values %d, %s", id, filename)
finally:
cursor.close()
我沒有足夠的聲譽發表評論,但這是一個重要的注意事項:
如果在調用后未提交,則execute()也可能以靜默方式失敗。 也就是說,MyISAM表不需要提交,但InnoDB會這樣做。
如果插入失敗,你會得到一個凸起的例外,或者有人會喊叫,否則你會從椅子上掉下來。
如何使用try / catch塊而不是查看rowcount。 如果它捕獲異常則存在問題; 否則,沒問題。
將insert語句存儲在字符串中並在之后打印。 如果發生異常,則不會打印語句。
sql_insert = """insert into new_files (videos_id, filename, is_processing)
values (%s,%s,1)"""
cur.execute(sql_insert)
print('Executed:', sql_insert)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.