实现还是比较简单的,通过warnings里的filterwarnings拦截
以后其他warnings也可以通过类似方法拦截
转自
-
from warnings import filterwarnings
-
filterwarnings('error', category = MySQLdb.Warning)
-
-
try:
-
conn = MySQLdb.connect(host=host,port=port,db=dbname,user=user,passwd=pwd)
-
cursor=conn.cursor()
-
cursor.execute(sql)
-
result = cursor.fetchall()
-
cursor.close()
-
conn.rollback()
-
conn.close()
-
except MySQLdb.Warning, w:
-
sqlWarning = "Warning:%s" % str(w)
-
except MySQLdb.Error, e:
-
sqlError = "Error:%s" % str(e)
error中 e[0] 或去error no, e[1] 获取具体msg
但是warning中不行
需要获取
warning需要如下方式
-
warning_no = -1
-
try:
-
# 忽略指定Warning
-
warning_no = int(conn.show_warnings()[0][1])
-
if warning_no == 1051:
-
loger.warning('index [%d] Warning, 一般由 DROP IF EXISTS 引发' % index)
-
continue
-
except IndexError:
-
loger.error('get Warning no index error')
-
except TypeError:
-
loger.error('get Warning no type error')
-
except ValueError:
-
loger.error('get Warning no value error')
show_warnings函数实际是调用exec执行
-
def show_warnings(self):
-
"""Return detailed information about warnings as a
-
sequence of tuples of (Level, Code, Message). This
-
is only supported in MySQL-4.1 and up. If your server
-
is an earlier version, an empty sequence is returned."""
-
if self._server_version < (4,1): return ()
-
self.query("SHOW WARNINGS")
-
r = self.store_result()
-
warnings = r.fetch_row(0)
-
return warnings
没测试是不是一堆warnings是不是会叠一起,所以最好捕获到warnings后马上调用一次show_warnings
阅读(1959) | 评论(0) | 转发(0) |