[英]Correct exception handling with python MySQLdb connection
我創建了一個小/基本的python腳本來將數據插入到MySQL數據庫中。 我包含了一些錯誤處理 - 主要是為了關閉連接和/或在出錯時防止掛起連接(......但也忽略了一些錯誤)。
我以為我擁有的東西(見下文)是對的 - 似乎工作正常。 但偶爾我會得到“連接太多”錯誤 - 我假設這意味着我實際上並沒有正確關閉連接(或者錯誤處理可能不正確)。
conn=MySQLdb.connect(host=####, user=####, passwd=####, db=####)
curs=conn.cursor()
try:
curs.execute(sql)
conn.commit()
except MySQLdb.Error as e:
if e[0]!= ###:
raise
finally:
curs.close()
conn.close()
(我finally:
也試過了finally:
另一個(我認為重要的)是MySQL數據庫使用InnoDB存儲引擎。 這是我第一次使用InnoDB引擎,也許MyISAM有一些與此相關的差異,我不知道(比如conn.commit()
,但是出錯了)....這似乎是我所有其他問題的根源!
提前致謝
我認為問題是我沒有在except
子句中調用conn.rollback()
(因此,連接沒有正確關閉)。 to fix the issue (I can't be exactly sure if that was this issue - if someone could confirm that would be great). 一行(見下文) 解決了這個問題(我不能確定這是否是這個問題 - 如果有人能證實那會很好)。
conn=MySQLdb.connect(host=####, user=####, passwd=####, db=####)
curs=conn.cursor()
try:
curs.execute(sql)
conn.commit()
except MySQLdb.Error as e:
conn.rollback() #rollback transaction here
if e[0]!= ###:
raise
finally:
curs.close()
conn.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.