在 Python 中捕获 MySQL 警告

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/647805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:32:16  来源:igfitidea点击:

Trapping MySQL Warnings In Python

pythonmysql

提问by chernevik

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.

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

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

try/except 语法确实会捕获 MySQL 错误(例如,提交类似 的拼写错误'DRP DATABASE database_of_armaments')。

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.

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

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

具体来说,我如何让以下(或类似的)工作。

GIVEN: database 'database_of_armaments' does not exist.

给定:数据库“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?>>

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.

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

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

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

Thank you for your help.

谢谢您的帮助。

采纳答案by S.Lott

Follow these steps.

跟着这些步骤。

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

  2. See what exception you get.

  3. Change the Exceptionto the exception you actually got.

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

  2. 看看你得到了什么异常。

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

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

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

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

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

回答by karlcow

Have you tried something like this?

你有没有尝试过这样的事情?

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

回答by dangerouslyfacetious

I think the exception you want to catch is a MySQLdb.ProgrammingError, and to get information about it, just add a variable to store the error data (a tuple) in after that i.e:

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

回答by Victor Gavro

first you should turn on warnings to treat as exceptions, and only then you can catch them. see "error" warnings filter - https://docs.python.org/3/library/warnings.html#the-warnings-filter

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

回答by rafaelxy

I managed to trap the mysql warning like this:

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

import _mysql_exceptions

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

回答by Christian

Plain and simple

干净利落

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] example :- (u'Warning', 1366L, u"Incorrect integer value: '\xa3' for column 'in_userid' at row 1")

msg[1] 示例:- (u'Warning', 1366L, u"Incorrect integer value: '\xa3' for column 'in_userid' at row 1")