代码之家  ›  专栏  ›  技术社区  ›  chernevik

包装在类中的MySQL警告-Python

  •  -1
  • chernevik  · 技术社区  · 15 年前

    当执行语句封装在类中时,我无法让Python的try/else块捕捉MySQL警告。

    我有一个类,它将MySQL连接对象作为一个属性,一个MySQL游标对象作为另一个属性,以及一个通过该游标对象运行查询的方法。游标本身被包装在一个类中。它们似乎可以正常运行查询,但它们生成的MySQL警告不会作为try/else块中的异常捕获。为什么try/else块没有捕捉到警告?如何修改类或方法调用以捕捉警告?

    另外,我已经查阅了大量的资料来源,但没有找到一个有助于我理解这一点的讨论。如果有人能解释这一点,我将不胜感激。

    请参阅下面的代码。抱歉,我是新手。

    #!/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'
    
    1 回复  |  直到 15 年前
        1
  •  0
  •   Kurt    15 年前

    乍一看至少有一个问题:

            if dict_flag:
            dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor)
    

    不是吗

             if dict_flag:
             self.dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor)
    

    你在混淆视听。我也会把

    self.conn = MySQLdb.connect(db_server, db_user, db_passwd)
    

    在try/except块中,因为我怀疑由于导入了db凭据,您可能没有正确创建数据库连接(我将抛出一个print语句以确保数据确实被传递)。