在Python中捕获MySQL警告

che*_*vik 14 python mysql

我想在Python中捕获并记录MySQL警告.例如,如果'DROP DATABASE IF EXISTS database_of_armaments'在没有此类数据库时提交,MySQL会向标准错误发出警告.我想抓住这个并记录它,但即使在try/else语法中,仍然会出现警告消息.

try/except语法确实捕获了MySQL错误(例如,提交类似的错字'DRP DATABASE database_of_armaments').

我已经尝试过<<except.MySQLdb.Warning>>- 没有运气.我查看了警告模块,但不明白如何将其合并到try/else语法中.

具体来说,我如何使以下(或类似的东西)工作.

GIVEN:数据库'database_of_armaments'不存在.

try:
    cursor.execute('DROP DATABASE IF EXISTS database_of_armaments')
except: <<WHAT DO I PUT HERE?>>
    print 'There was a MySQL warning.' 
    <<AND what goes here if I want to get and manipulate information about the warning?>>
Run Code Online (Sandbox Code Playgroud)

更新:

感谢您的评论.我试过这些并且它们没有用 - 但是我一直在使用我为连接编写的DatabaseConnection类,以及要执行的runQuery()方法.当我在类外部创建一个连接和光标时,try/except异常捕获了"编程错误",除了MySQLdb.ProgrammingError工作的广告.

所以现在我必须弄清楚我的类编码有什么问题.

谢谢您的帮助.

S.L*_*ott 15

跟着这些步骤.

  1. 运行它except Exception, e: print repr(e).

  2. 看看你得到了什么例外.

  3. 更改为Exception您实际获得的异常.

另外,请记住,异常e是一个对象.您可以打印dir(e),e.__class__.__name__,etc.to看看它有哪些属性.

此外,您可以>>>在Python 的提示符下以交互方式执行此操作.然后你可以直接操纵对象 - 不要猜测.


kar*_*cow 7

你尝试过这样的事吗?

try:
    cursor.execute(some_statement)
except MySQLdb.IntegrityError, e: 
    # handle a specific error condition
except MySQLdb.Error, e:
    # handle a generic error condition
except MySQLdb.Warning, e:
    # handle warnings, if the cursor you're using raises them
Run Code Online (Sandbox Code Playgroud)