Trappings MySQL Warnings on Calls Wrapped in Classes -- Python

Posted by chernevik on Stack Overflow See other posts from Stack Overflow or by chernevik
Published on 2009-03-16T17:26:59Z Indexed on 2010/06/03 13:04 UTC
Read the original article Hit count: 239

Filed under:
|

I can't get Python's try/else blocks to catch MySQL warnings when the execution statements are wrapped in classes.

I have a class that has as a MySQL connection object as an attribute, a MySQL cursor object as another, and a method that run queries through that cursor object. The cursor is itself wrapped in a class. These seem to run queries properly, but the MySQL warnings they generate are not caught as exceptions in a try/else block. Why don't the try/else blocks catch the warnings? How would I revise the classes or method calls to catch the warnings?

Also, I've looked through the prominent sources and can't find a discussion that helps me understand this. I'd appreciate any reference that explains this.

Please see code below. Apologies for verbosity, I'm newbie.

#!/usr/bin/python
import MySQLdb
import sys
import copy
sys.path.append('../../config')
import credentials as c # local module with dbase connection credentials
#=============================================================================
# CLASSES
#------------------------------------------------------------------------
class dbMySQL_Connection:
    def __init__(self, db_server, db_user, db_passwd):
        self.conn = MySQLdb.connect(db_server, db_user, db_passwd)
    def getCursor(self, dict_flag=True):
        self.dbMySQL_Cursor = dbMySQL_Cursor(self.conn, dict_flag)
        return self.dbMySQL_Cursor
    def runQuery(self, qryStr, dict_flag=True):
        qry_res = runQueryNoCursor(qryStr=qryStr, \
                                   conn=self, \
                                   dict_flag=dict_flag)
        return qry_res
#------------------------------------------------------------------------
class dbMySQL_Cursor:
    def __init__(self, conn, dict_flag=True):
        if dict_flag:
            dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor)
        else:
            dbMySQL_Cursor = conn.cursor()
        self.dbMySQL_Cursor = dbMySQL_Cursor
    def closeCursor(self):
        self.dbMySQL_Cursor.close()
#=============================================================================
# QUERY FUNCTIONS
#------------------------------------------------------------------------------
def runQueryNoCursor(qryStr, conn, dict_flag=True):
    dbMySQL_Cursor = conn.getCursor(dict_flag)
    qry_res =runQueryFnc(qryStr, dbMySQL_Cursor.dbMySQL_Cursor)
    dbMySQL_Cursor.closeCursor()
    return qry_res
#------------------------------------------------------------------------------
def runQueryFnc(qryStr, dbMySQL_Cursor):
    qry_res              = {}
    qry_res['rows']      = dbMySQL_Cursor.execute(qryStr)
    qry_res['result']    = copy.deepcopy(dbMySQL_Cursor.fetchall())
    qry_res['messages']  = copy.deepcopy(dbMySQL_Cursor.messages)
    qry_res['query_str'] = qryStr
    return qry_res
#=============================================================================
# USAGES
qry = 'DROP DATABASE IF EXISTS database_of_armaments'
dbConn = dbMySQL_Connection(**c.creds)
def dbConnRunQuery():
    # Does not trap an exception; warning displayed to standard error.
    try:
        dbConn.runQuery(qry)
    except:
        print "dbConn.runQuery() caught an exception."
def dbConnCursorExecute():
    # Does not trap an exception; warning displayed to standard error.
    dbConn.getCursor()  # try/except block does catches error without this
    try:
        dbConn.dbMySQL_Cursor.dbMySQL_Cursor.execute(qry)
    except Exception, e:
        print "dbConn.dbMySQL_Cursor.execute() caught an exception."
        print repr(e)
def funcRunQueryNoCursor():
    # Does not trap an exception; no warning displayed
    try:
        res = runQueryNoCursor(qry, dbConn)
        print 'Try worked. %s' % res
    except Exception, e:
        print "funcRunQueryNoCursor() caught an exception."
        print repr(e)
#=============================================================================
if __name__ == '__main__':
    print '\n'
    print 'EXAMPLE -- dbConnRunQuery()'
    dbConnRunQuery()
    print '\n'
    print 'EXAMPLE -- dbConnCursorExecute()'
    dbConnCursorExecute()
    print '\n'
    print 'EXAMPLE -- funcRunQueryNoCursor()'
    funcRunQueryNoCursor()
    print '\n'

© Stack Overflow or respective owner

Related posts about python

Related posts about mysql