捕获一个MySql警告 [英] trapping a MySql warning

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

问题描述

在我的python脚本中,我想使用MySql捕获我的查询的列数据被截断"警告.

In my python script I would like to trap a "Data truncated for column 'xxx'" warning durnig my query using MySql.

我在下面看到了一些建议代码的帖子,但这没用.

I saw some posts suggesting the code below, but it doesn' work.

您知道在使用此代码之前是否必须导入某些特定模块或是否应调用某些选项/标志吗?

Do you know if some specific module must be imported or if some option/flag should be called before using this code?

谢谢

Afeg

import MySQLdb
try:
    cursor.execute(some_statement)
    # code steps always here: No Warning is trapped
    # by the code below
except MySQLdb.Warning, e:
    # handle warnings, if the cursor you're using raises them
except Warning, e:
    # handle warnings, if the cursor you're using raises them

推荐答案

警告仅仅是:警告.他们被报告给(通常)stderr,但是没有做其他事情.您无法像异常一样捕获它们,因为它们没有被引发.

Warnings are just that: warnings. They get reported to (usually) stderr, but nothing else is done. You can't catch them like exceptions because they aren't being raised.

但是,您可以使用warnings模块配置带有警告的 操作,然后将其关闭或将其变为异常.例如,warnings.filterwarnings('error', category=MySQLdb.Warning)可以将MySQLdb.Warning warnings转换为异常(在这种情况下,将使用try/except捕获它们)或'ignore'根本不显示它们.您可以(也许应该)拥有比类别更多的细粒度过滤器.

You can, however, configure what to do with warnings, and turn them off or turn them into exceptions, using the warnings module. For instance, warnings.filterwarnings('error', category=MySQLdb.Warning) to turn MySQLdb.Warning warnings into exceptions (in which case they would be caught using your try/except) or 'ignore' to not show them at all. You can (and probably should) have more fine-grained filters than just the category.

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

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