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函數讀取全局變量連接。我確定這不是一個前向參考問題,因爲我以這種方式進行了測試。使用全局全局名稱管理數據庫連接消失
爲連接使用全局變量的目的是在所有函數中重新使用連接而不必每次創建新連接。
請包括*完整回溯*。 –
請注意,您編寫的代碼將在每次創建實例時*替換* global * connection;你在這裏沒有重複使用任何東西。順便說一句,您可以使用類屬性而不是全局屬性; 'connection = None' at class level,then'if not MyAddon.connection:MyAddon.connection = ...';任何* read *'self.connection'的嘗試都會找到共享類的屬性。 –