首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python mysqldb游标消息列表显示两次错误

问python mysqldb游标消息列表显示两次错误
EN

Stack Overflow用户
提问于 2010-07-24 13:13:48
回答 1查看 1.7K关注 0票数 2

由于某些原因,每当我在db游标上运行查询时,它在其.messages列表中生成两个错误,这是一个特性吗?

下面是运行查询的代码,应用程序所做的就是打开到数据库的连接,运行一次强制错误,读取.messages,然后退出

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-07-24 13:53:54

也许您可以发布您收到的消息。

mysql_insert_etc.py:22:警告:第1行的列'val‘的数据被截断

self.cursor.execute(query,args) (,('Warning',1265L,“第1行'val‘列的数据被截断”)

从上面(制造的错误)可以看出,MySQLdb返回:

  1. MySQL warning,
  2. 自己的异常。

使用下面的代码,您可以禁止显示警告,也可以让警告引发异常。

引发异常(对this example稍作修改):

代码语言:javascript
复制
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

Suppress warnings (from here):

代码语言:javascript
复制
from warnings import filterwarnings

filterwarnings('ignore', category=MySQLdb.Warning)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3323918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档