python mysql捕获异常_在Python中捕获MySQL警告

bd96500e110b49cbb3cd949968f18be7.png

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.

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

I have experimented with <> -- 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.

GIVEN: database 'database_of_armaments' does not exist.

try:

cursor.execute('DROP DATABASE IF EXISTS database_of_armaments')

except: <>

print 'There was a MySQL warning.'

<>

UPDATE:

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.

Thank you for your help.

解决方案

Follow these steps.

Run it with except Exception, e: print repr(e).

See what exception you get.

Change the Exception to the exception you actually got.

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值