在我的python脚本中,我想捕获"数据截断列'xxx'"警告使用MySql查询我的查询.
我看到一些帖子提示下面的代码,但它没有用.
您是否知道在使用此代码之前是否必须导入某个特定模块或是否应调用某个选项/标志?
谢谢大家
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
Run Code Online (Sandbox Code Playgroud)
Tho*_*ers 47
警告只是:警告.他们被报告(通常)stderr,但没有其他任何事情.你不能像异常一样抓住它们,因为它们没有被提升.
你可以,但是,配置怎么做有警告,并关闭它们或者将它们变成例外,使用warnings模块.例如,warnings.filterwarnings('error', category=MySQLdb.Warning)转换MySQLdb.Warning warnings为异常(在这种情况下,它们将使用您的try/except捕获)或'ignore'根本不显示它们.您可以(也可能应该)拥有比类别更细粒度的过滤器.
Rak*_*kib 12
将MySQL警告提升为错误:
import warnings, MySQLdb
warnings.filterwarnings('error', category=MySQLdb.Warning)
Run Code Online (Sandbox Code Playgroud)
要忽略而不是引发错误,请替换"error"为"ignore".
在try-except块中处理它们,如:
try:
# a MySQL DB operation that raises a warning
# for example: a data truncated warning
except Warning as a_warning:
# do something here
Run Code Online (Sandbox Code Playgroud)
我将首先尝试设置sql_mode。您可以在会话级别执行此操作。如果执行以下操作:
SET @@sql_mode:=TRADITIONAL;
Run Code Online (Sandbox Code Playgroud)
(您也可以在服务器级别设置它,但是您需要访问服务器才能执行此操作。并且,在会话级别设置仍然被覆盖,因此,最重要的是,始终将其立即设置为会话级别建立连接后)
那么许多通常是警告的东西就会变成错误。我不知道它们是如何在python级别上表现出来的,但是明显的好处是更改不会存储在数据库中。参见:http : //dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html#sqlmode_traditional
如果你想让它忽略它,请参阅Python文档中的"暂时禁止警告":
https://docs.python.org/2/library/warnings.html#temporarily-suppressing-warnings
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Put here your query raising a warning
Run Code Online (Sandbox Code Playgroud)
另外,只需阅读有关Python的"警告"模块的文档,如果您想稍后捕获它们,可以将它们转换为异常......等等......这些都在这里:https://docs.python.org/2/library/ warnings.html
| 归档时间: |
|
| 查看次数: |
20446 次 |
| 最近记录: |