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函数读取全局变量连接。我确信这不是一个前向参考问题,因为我是这样测试的。在
将全局变量用于连接的目的是在所有函数中重用连接,而不必每次都创建新的连接。在
可能是Kodi对名称空间做了一些奇怪的事情,或者您的实例被pickle了;当取消pickle时,全局将消失。像这样的全局的另一个问题是连接可能在某个时刻丢失。在
我将重新构造代码,使其具有返回连接的方法,并在所有需要连接的方法中使用该方法。使连接方法成为classmethod,并允许连接消失:
我在
connect
类方法中引发一个异常;您需要决定如何处理数据库配置错误或无法连接的情况。仅显示错误消息是不够的。当然,仍然可以从__init__
方法调用self.connect()
来提前通知这个问题。在相关问题 更多 >
编程相关推荐