[英]Trapping MySQL Warnings In Python
我想在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?>>
更新:
感谢您的评论。 我曾尝试过这些并且它们不起作用 - 但我一直在使用我为连接编写的DatabaseConnection类,以及要执行的runQuery()方法。 当我在类外部创建一个连接和光标时,try / except异常捕获了“编程错误”,除了MySQLdb.ProgrammingError工作的广告。
所以现在我必须弄清楚我的类编码有什么问题。
谢谢您的帮助。
跟着这些步骤。
运行它except Exception, e: print repr(e)
。
看看你得到了什么例外。
将Exception
更改为您实际获得的异常。
另外,请记住,异常e是一个对象。 您可以打印dir(e)
, e.__class__.__name__
等,以查看它具有的属性。
此外,您可以在Python的>>>
提示符下以交互方式执行此操作。 然后你可以直接操纵对象 - 不要猜测。
你尝试过这样的事吗?
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
我认为您要捕获的异常是MySQLdb.ProgrammingError,并且要获取有关它的信息,只需添加一个变量来存储错误数据(元组),即:
try:
cursor.execute('DROP DATABASE IF EXISTS database_of_armaments')
except MySQLdb.ProgrammingError, e:
print 'There was a MySQL warning. This is the info we have about it: %s' %(e)
我设法捕获这样的mysql警告:
import _mysql_exceptions
try:
foo.bar()
except _mysql_exceptions.Warning, e:
pass
首先,您应该打开警告以视为异常,然后才能捕获它们。 请参阅“错误”警告过滤器 - https://docs.python.org/3/library/warnings.html#the-warnings-filter
干净利落
def log_warnings(curs):
for msg in curs.messages:
if msg[0] == MySQLdb.Warning:
logging.warn(msg[1])
cursor.execute('DROP DATABASE IF EXISTS database_of_armaments')
log_warnings(cursor)
msg [1]示例: - (u'Warning', 1366L, u"Incorrect integer value: '\\xa3' for column 'in_userid' at row 1")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.