python mysqldb 游标消息列表错误显示两次
不知道为什么,每次我在数据库游标上运行查询时,它的 .messages 列表里都会生成两个错误,这算不算一种特性呢?
下面是运行查询的代码,整个应用程序的工作就是打开一个与数据库的连接,强制产生一个错误后运行这个查询,读取 .messages,然后退出。
import MySQLdb
class dbobject:
def __init__(self, dbhost, dbuser, dbpass, dbname):
self.connection = MySQLdb.connect( user=dbuser, passwd=dbpass, host=dbhost, db=dbname )
self.cursor = self.connection.cursor()
def try_query(self, query, args=()):
""" attempts to run a query, where
query is the query to be run, with '%s' statements where the values should be, and
args is a tuple of the values to go with the query"""
try:
if args == ():
self.cursor.execute(query)
else:
self.cursor.execute(query, args)
self.connection.commit()
except:
self.connection.rollback()
def add_unit(self, name, version, credits):
""" takes name, version, credits
name is the name of the unit paper
version is the unit version, and
credits is how many credits its worth"""
self.try_query("insert into dsfdf tbl_unit (unit_name, unit_version, unit_credits) values (%s,%s,%s)",(name,version,credits))
def close(self):
self.cursor.close()
self.connection.close()
blah = dbobject(#####################)
blah.add_unit( "thing", "something", 6)
for i in blah.cursor.messages:
print i
blah.close()
1 个回答
1
也许你可以把你收到的消息发出来。
mysql_insert_etc.py:22: 警告:数据在第1行的'val'列被截断
self.cursor.execute(query, args) (, ('警告', 1265L, "数据在第1行的'val'列被截断"))
从上面的(制造的错误)来看,MySQLdb 返回了:
- MySQL 的警告,和
- 它自己的异常。
使用下面的代码,你可以选择要么抑制警告,要么让它们引发异常。
引发异常(稍微修改自 这个例子):
from warnings import catch_warnings, simplefilter
def try_query(self, query, args=()):
with catch_warnings():
simplefilter('error', MySQLdb.Warning)
try:
if args == ():
self.cursor.execute(query)
else:
self.cursor.execute(query, args)
self.connection.commit()
except MySQLdb.Error, e:
self.connection.rollback()
raise e
抑制警告(来自这里):
from warnings import filterwarnings
filterwarnings('ignore', category=MySQLdb.Warning)