使用 python MySQLdb 连接正确处理异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21721109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct exception handling with python MySQLdb connection
提问by djmac
I created a small/basic python script to insert data into a MySQL database. I included some error handling - mainly to close the connection and/or prevent hanging connections in the case of an error (...but also to ignore some errors).
我创建了一个小型/基本的 python 脚本来将数据插入到 MySQL 数据库中。我包括了一些错误处理 - 主要是为了在出现错误时关闭连接和/或防止挂起连接(...但也忽略一些错误)。
I thought what I had (see below) was right - it seemed to be working okay. But occasionally I have been getting "Too many connection" errors - which I assumes means I am not actually closing the connection correctly at all (or perhaps error handling isn't right).
我认为我所拥有的(见下文)是正确的 - 它似乎工作正常。但偶尔我会收到“连接过多”错误 - 我认为这意味着我实际上根本没有正确关闭连接(或者错误处理可能不正确)。
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()
(I also tried without finally:)
(我也试过没有finally:)
The other (I think important) point is that it is that the MySQL database uses an InnoDB storage engine. This is the first time I have used InnoDB engine and perhaps there are some differences to MyISAM that are relevant here, that I am not aware of (like conn.commit(), but for an error).... That seems to be the source of all my other problems!
另一点(我认为很重要)是 MySQL 数据库使用 InnoDB 存储引擎。这是我第一次使用 InnoDB 引擎,也许这里有一些与 MyISAM 相关的差异,我不知道(比如conn.commit(),但是有一个错误)......这似乎是我所有其他问题!
Thanks in advance
提前致谢
回答by djmac
I believe the issue was I wasn't invoking conn.rollback()in the exceptclause (and consequently, the connection was not closing properly). One line (see below) seemedto fix the issue (I can't be exactly sure if that was this issue - if someone could confirm that would be great).
我相信问题是我没有conn.rollback()在except子句中调用(因此,连接没有正确关闭)。一行(见下文)似乎解决了这个问题(我不能完全确定这是否是这个问题——如果有人能确认那会很棒)。
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()

