Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在类包装的调用上附加MySQL警告——Python_Python_Mysql - Fatal编程技术网

在类包装的调用上附加MySQL警告——Python

在类包装的调用上附加MySQL警告——Python,python,mysql,Python,Mysql,当执行语句包装在类中时,我无法让Python的try/else块捕捉MySQL警告 我有一个类,它有一个MySQL连接对象作为属性,一个MySQL游标对象作为另一个属性,还有一个通过该游标对象运行查询的方法。游标本身包装在一个类中。这些查询似乎可以正常运行,但它们生成的MySQL警告不会作为异常捕获到try/else块中。为什么try/else块不捕捉警告?如何修改类或方法调用以捕获警告 此外,我已经查阅了重要的资料来源,但找不到有助于我理解这一点的讨论。如果有任何能解释这一点的参考资料,我将不

当执行语句包装在类中时,我无法让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'

乍一看,至少有一个问题:

        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语句以确保数据确实被传递)

你在期待什么?你能把代码缩减到最小的例子来说明问题吗?还有,为什么这么复杂?你想优化什么?为什么有调用全局函数的类?显示了哪些警告?警告不一定与异常相同。