异常和警告处理案例
# -*- coding: UTF-8 -*-
import MySQLdb
#警告信息try except是无法捕捉的
from warnings import filterwarnings
filterwarnings('error', category = MySQLdb.Warning)
#当然也可以屏蔽警告filterwarnings("ignore")
try:
conn = MySQLdb.connect(host='127.0.0.1',user='test',passwd='test',db='test',port=3306,charset='utf8')
cursor = conn.cursor()
#创建表
create_tabl_sql = """CREATE TABLE IF NOT EXISTS `test1` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`create_time` datetime NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8"""
cursor.execute(create_tabl_sql)
cursor.close()
conn.close()
except MySQLdb.Warning, w:
print "警告信息 %s" % str(w)
except MySQLdb.Error, e:
print "错误信息 %d %s" % (e.args[0], e.args[1])