Catching warnings from the MySQLdb module

The MySQLdb Python module implements the Python DB API for MySQL. I’ve written about its use before. MySQL issues warning messages in a number of circumstances and PEP 249 (which specifies the Python DB API) describes a Warning error message to be included.

One issue I ran into recently was how to catch warnings thrown by this module when running queries. Oftentimes tutorials or forum discussions that cover warnings in the context of MySQLdb describe how to filter them (they can clog up script output). But in a recent case I wanted to grab and check the warning, logging a dependent result. I had hoped this clean implementation would work in a method used for all calls to the MySQL DB:

1
2
3
4
5
6
7
8
9
10
11
try:
    cursor.execute(query)
except MySQLdb.Error, e:
    raise e
except MySQLdb.Warning, e:
    raise e
finally:
    data = cursor.fetchall()
    rows_returned = cursor.rowcount
    cursor.close()
    db.close()

But the warnings just went right through. Instead I needed the warnings module’s assistance:

1
2
3
4
5
6
7
8
9
10
11
12
import warnings
with warnings.catch_warnings():
    warnings.simplefilter('error', MySQLdb.Warning)
    try:
        cursor.execute(query)
    except MySQLdb.Error, e:
        raise e
    finally:
        data = cursor.fetchall()
        rows_returned = cursor.rowcount
        cursor.close()
        db.close()

This catches the warnings and raises them as errors, although their class is still correct, allowing a clean implementation to call the above code (wrapped into a method called do_query):

1
2
3
4
5
try:
    self.do_query(make_cool_table)
    logger.info("Created cool_table table.")
except MySQLdb.Warning:
    logger.info("cool_table already exists.")
Be Sociable, Share!

Post to Twitter Post to Delicious Post to Digg Post to Reddit

This entry was posted in Python and tagged , , . Bookmark the permalink.

4 Responses to Catching warnings from the MySQLdb module

  1. Pingback: Catching Python MySQL Exceptions « Octopus Grabus' Log

  2. Thanks for posting this. I cross-referenced it in my blog.

  3. Pingback: A Good Example of Time Wasted « Dr. Knucklehead's Blog

  4. In fact, we didn¡¯t even discover those boxes until the centre of the show up.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>