使用全局全局名称管理数据库连接会消失

时间:2016-04-06 08:09:36

标签: python global-variables kodi

class MyAddon(pyxbmct.AddonDialogWindow):
    def __init__(self, title=''):
        super(MyAddon, self).__init__(title)
        self.mysql_connect()
        self.populate()

    def populate(self):
        categories = self.read_data()

    def read_data(self):
        query = ("SELECT category FROM test")
        cursor = connection.cursor()
        categories = cursor.execute(query)
        return categories

    def mysql_connect(self):
        global connection
        try:
            connection = mysql.connector.connect(**config).cursor()
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                xbmc.executebuiltin('Notification(Error!, Bad user name of password)')
            elif err.errno == errorcode.ER_BAD_DB_ERROR:
                xbmc.executebuiltin('Notification(Error!, Database does not exist)')
            else:
                xbmc.executebuiltin('Notification(Error!, {0})'.format(err))

我正在为Kodi开发一个Python附加组件。尝试将全局变量用于数据库连接时,出现Global name 'connection' is not defined错误。我无法从read_data函数中读取全局变量连接。我确定这不是一个前向引用问题,因为我是这样测试的。

使用全局变量进行连接的目的是在所有函数中重用连接,而不是每次都创建新连接。

1 个答案:

答案 0 :(得分:3)

Kodi可能会使用命名空间做一些时髦的事情,或者你的实例被腌制;当破坏时,全球将会消失。像这样的全局的另一个问题是连接可能在某些时候丢失。

我重新构造代码以获得一个返回连接的方法,并在需要连接的所有方法中使用它。使连接方法成为类方法,允许连接消失

class MyAddonConnectionFailed(Exception): pass

def read_data(self):
    query = ("SELECT category FROM test")
    try:
        conn = self.connect()
    except MyAddonConnectionFailed:
        # connection failed; error message already displayed
        return []
    cursor = conn.cursor()
    categories = cursor.execute(query)
    return categories

_connection = None

@classmethod
def connect(cls):
    if cls._connection and cls._connection.open:
        return cls._connection

    try:
        cls._connection = mysql.connector.connect(**config).cursor()
        return cls._connection
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            xbmc.executebuiltin('Notification(Error!, Bad user name of password)')
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            xbmc.executebuiltin('Notification(Error!, Database does not exist)')
        else:
            xbmc.executebuiltin('Notification(Error!, {0})'.format(err))
     raise MyAddonConnectionFailed

我在connect班级方法中提出异常;您需要决定如何处理数据库配置错误或无法连接的情况。显示错误消息是不够的。 仍然可以通过self.connect()方法调用__init__来提前发出此问题。