在Python中捕获MySQL警告 [英] Trapping MySQL Warnings In Python

查看:433
本文介绍了在Python中捕获MySQL警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Python捕获并记录MySQL警告.例如,如果您在没有这样的数据库存在的情况下提交'DROP DATABASE IF EXISTS database_of_armaments',MySQL会向标准错误发出警告.我想捕获并记录下来,但是即使在try/else语法中,警告消息仍然会出现.

I would like to catch and log MySQL warnings in Python. For example, MySQL issues a warning to standard error if you submit 'DROP DATABASE IF EXISTS database_of_armaments' when no such database exists. I would like to catch this and log it, but even in the try/else syntax the warning message still appears.

try/except语法确实捕获MySQL错误(例如,提交像'DRP DATABASE database_of_armaments'这样的拼写错误).

The try/except syntax does catch MySQL errors (eg, submission of a typo like 'DRP DATABASE database_of_armaments').

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

I have experimented with <<except.MySQLdb.Warning>> -- no luck. I've looked at the warnings module, but don't understand how to incorporate it into the try/else syntax.

具体来说,如何使以下内容(或类似内容)正常工作.

To be concrete, how do I get the following (or something like it) to work.

鉴于:数据库'database_of_armaments'不存在.

GIVEN: database 'database_of_armaments' does not exist.

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?>>

更新:

感谢您的评论.我尝试了这些,但它们没有用-但是我一直在使用为连接编写的DatabaseConnection类,并使用其runQuery()方法执行.当我在类外创建连接和游标时,try/except Exception捕获了"Programming Error",而MySQLdb.ProgrammingError除外,其工作方式如所宣传.

Thanks for the comments. I had tried these and they didn't work -- but I had been using a DatabaseConnection class that I wrote for a connection, and its runQuery() method to execute. When I created a connection and cursor outside the class, the try/except Exception caught the "Programming Error", and except MySQLdb.ProgrammingError worked as advertised.

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

So now I have to figure out what is wrong with my class coding.

谢谢您的帮助.

推荐答案

请按照以下步骤操作.

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

看看你得到什么异常.

Exception更改为您实际遇到的异常.

Change the Exception to the exception you actually got.

此外,请记住,异常e是一个对象.您可以打印dir(e)e.__class__.__name__等以查看其具有的属性.

Also, remember that the exception, e, is an object. You can print dir(e), e.__class__.__name__, etc.to see what attributes it has.

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

Also, you can do this interactively at the >>> prompt in Python. You can then manipulate the object directly -- no guessing.

这篇关于在Python中捕获MySQL警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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