MySQLdb捕捉警告信息

使用MySQLdb(MySQL的python连接客户端)时可以通过try...except...捕捉到错误信息,比如:
import MySQLdb

try:
	conn = MySQLdb.connect(host=host,port=port,db=dbname,user=user,passwd=pwd)
except MySQLdb.Error, e:
        try:
            sqlError =  "Error %d:%s" % (e.args[0], e.args[1])
        except IndexError:
            print "MySQL Error:%s" % str(e)

cursor=conn.cursor()
try:
        cursor.execute(sql)
	result = cursor.fetchall()
	cursor.close()
        conn.rollback()
	conn.close()
except MySQLdb.Error, e:
        try:
            sqlError =  "Error %d:%s" % (e.args[0], e.args[1])
        except IndexError:
            print "MySQL Error:%s" % str(e)

但是如果我们想在程序里同时捕获警告信息而不仅仅是错误信息该怎么办?可能会自然而然的想到:
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)

但实际运行一个包含警告信息的SQL语句后发现程序并未捕获警告。为什么呢??这是因为python程序try...except...默认只能捕获到错误异常。
为了捕获到MySQLdb.Warning,我们可以更改MySQLdb.Warning的级别,让python程序认为这是一个错误,从而捕捉到它。为此需做一下操作:
from warnings import filterwarnings
filterwarnings(‘error‘, category = MySQLdb.Warning)
之后便可以通过try...except..结构捕获到这个异常了。

另外若想及捕获MySQLdb的警告由捕获MySQLdb的错误则可以使用一下结构:
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)







MySQLdb捕捉警告信息,布布扣,bubuko.com

MySQLdb捕捉警告信息

上一篇:RHEL平台升级Oracle 12C+ PSU补丁


下一篇:WebService 打开 ACCESS 不能使用;文件已在使用中的解决办法