在Python中捕获MySQL警告

时间:2009-03-15 13:25:52

标签: 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?>>

更新:

感谢您的评论。我曾尝试过这些并且它们不起作用 - 但我一直在使用我为连接编写的DatabaseConnection类,以及要执行的runQuery()方法。当我在类外部创建一个连接和光标时,try / except异常捕获了“编程错误”,除了MySQLdb.ProgrammingError之外,就像宣传的一样。

所以现在我必须弄清楚我的班级编码有什么问题。

感谢您的帮助。

6 个答案:

答案 0 :(得分:15)

请按照以下步骤操作。

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

  2. 查看您获得的例外情况。

  3. Exception更改为您实际获得的例外情况。

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

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

答案 1 :(得分: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

答案 2 :(得分:2)

我认为您要捕获的异常是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) 

答案 3 :(得分:1)

首先你应该打开警告来视为异常,然后才能捕获它们。 请参阅“错误”警告过滤器 - https://docs.python.org/3/library/warnings.html#the-warnings-filter

答案 4 :(得分:1)

我设法捕获了这样的mysql警告:

import _mysql_exceptions

try:
    foo.bar()
except _mysql_exceptions.Warning, e:
    pass

答案 5 :(得分:0)

简单明了

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

相关问题