Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1102572
  • 博文数量: 170
  • 博客积分: 1603
  • 博客等级: 上尉
  • 技术积分: 1897
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-09 15:54
文章分类

全部博文(170)

文章存档

2016年(27)

2015年(21)

2014年(27)

2013年(21)

2012年(7)

2011年(67)

我的朋友

分类: Python/Ruby

2014-07-11 18:44:59

实现还是比较简单的,通过warnings里的filterwarnings拦截
以后其他warnings也可以通过类似方法拦截

转自

点击(此处)折叠或打开

  1. from warnings import filterwarnings
  2.     filterwarnings('error', category = MySQLdb.Warning)

  3.     try:
  4.         conn = MySQLdb.connect(host=host,port=port,db=dbname,user=user,passwd=pwd)
  5.         cursor=conn.cursor()
  6.         cursor.execute(sql)
  7.         result = cursor.fetchall()
  8.         cursor.close()
  9.             conn.rollback()
  10.         conn.close()
  11.     except MySQLdb.Warning, w:
  12.             sqlWarning = "Warning:%s" % str(w)
  13.     except MySQLdb.Error, e:
  14.             sqlError = "Error:%s" % str(e)

error中 e[0] 或去error no, e[1] 获取具体msg
但是warning中不行

需要获取warning需要如下方式

点击(此处)折叠或打开

  1.                         warning_no = -1
  2.                         try:
  3.                             # 忽略指定Warning
  4.                             warning_no = int(conn.show_warnings()[0][1])
  5.                             if warning_no == 1051:
  6.                                 loger.warning('index [%d] Warning, 一般由 DROP IF EXISTS 引发' % index)
  7.                                 continue
  8.                         except IndexError:
  9.                             loger.error('get Warning no index error')
  10.                         except TypeError:
  11.                             loger.error('get Warning no type error')
  12.                         except ValueError:
  13.                             loger.error('get Warning no value error')

show_warnings函数实际是调用exec执行

点击(此处)折叠或打开

  1. def show_warnings(self):
  2.         """Return detailed information about warnings as a
  3.         sequence of tuples of (Level, Code, Message). This
  4.         is only supported in MySQL-4.1 and up. If your server
  5.         is an earlier version, an empty sequence is returned."""
  6.         if self._server_version < (4,1): return ()
  7.         self.query("SHOW WARNINGS")
  8.         r = self.store_result()
  9.         warnings = r.fetch_row(0)
  10.         return warnings
没测试是不是一堆warnings是不是会叠一起,所以最好捕获到warnings后马上调用一次show_warnings



阅读(1845) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~