使用python MySQLdb连接正确异常处理 [英] Correct exception handling with python MySQLdb connection

查看:131
本文介绍了使用python MySQLdb连接正确异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个小型/基本的python脚本将数据插入到MySQL数据库中。我包括一些错误处理 - 主要是关闭连接和/或防止在出现错误的情况下挂起连接(...也可以忽略一些错误)。

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).

我以为我有(见下))是对的 - 似乎工作正常。但偶尔我已经得到连接太多错误 - 我认为这意味着我实际上没有正确关闭连接(或者错误处理不正确)。

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()

(我也试过没有 finally: / code>)

(I also tried without finally:)

另一个(我认为重要的)要点是,MySQL数据库使用InnoDB存储引擎。这是我第一次使用InnoDB引擎,也许与MyISAM有一些相关的区别,我不知道(像 conn.commit(),但是一个错误)....这似乎是我所有其他问题的根源!

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!

提前感谢

推荐答案

我认为问题是我没有在中调用 conn.rollback()除了子句(因此连接没有正确关闭)。一行(见下文)似乎来解决问题(我不能确定是否这是这个问题 - 如果有人可以确认这将是好的)。

I believe the issue was I wasn't invoking conn.rollback() in the except clause (and consequently, the connection was not closing properly). 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()

这篇关于使用python MySQLdb连接正确异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆