python捕获mysql Warning

2040阅读 0评论2014-07-11 lolizeppelin
分类:Python/Ruby

实现还是比较简单的,通过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



上一篇:Mysql去除完全重复行语句
下一篇:MySQL innodb优化总结