tags:

views:

18

answers:

1

For some reason whenever i run a query on the db cursor, it generates two errors in its .messages list, is this a feature?

here is the code that runs the query, all the application does is open a connection to the db, run this once with a forced error, read the .messages, then exit

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()
A: 

Perhaps you can post the message(s) you receive.

mysql_insert_etc.py:22: Warning: Data truncated for column 'val' at row 1
self.cursor.execute(query, args) (, ('Warning', 1265L, "Data truncated for column 'val' at row 1"))

From the above (manufactured error) it appears that MySQLdb returns:

  1. the MySQL warning, and
  2. its own exception.

Using the code below you can either suppress warnings, or have them raise exceptions.

Raise an exception (slightly modified from this example):

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):

from warnings import filterwarnings

filterwarnings('ignore', category=MySQLdb.Warning)
Adam Bernier
Thanks, was ultimately trying to make an error log of incorrect queries, and used the information from the exception instead, should've thought of that earlier
biokiwi
Cheers. Glad to be of assistance. Btw, welcome to SO!
Adam Bernier