简体   繁体   English

使用python MySQLdb连接纠正异常处理

[英]Correct exception handling with python MySQLdb connection

I created a small/basic python script to insert data into a MySQL database. 我创建了一个小/基本的python脚本来将数据插入到MySQL数据库中。 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). 我包含了一些错误处理 - 主要是为了关闭连接和/或在出错时防止挂起连接(......但也忽略了一些错误)。

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:也试过了finally:

The other (I think important) point is that it is that the MySQL database uses an InnoDB storage engine. 另一个(我认为重要的)是MySQL数据库使用InnoDB存储引擎。 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! 这是我第一次使用InnoDB引擎,也许MyISAM有一些与此相关的差异,我不知道(比如conn.commit() ,但是出错了)....这似乎是我所有其他问题的根源!

Thanks in advance 提前致谢

I believe the issue was I wasn't invoking conn.rollback() in the except clause (and consequently, the connection was not closing properly). 我认为问题是我没有在except子句中调用conn.rollback() (因此,连接没有正确关闭)。 One line (see below) seemed 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM