2016-04-06 112 views
0
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函數讀取全局變量連接。我確定這不是一個前向參考問題,因爲我以這種方式進行了測試。使用全局全局名稱管理數據庫連接消失

爲連接使用全局變量的目的是在所有函數中重新使用連接而不必每次創建新連接。

+0

請包括*完整回溯*。 –

+1

請注意,您編寫的代碼將在每次創建實例時*替換* global * connection;你在這裏沒有重複使用任何東西。順便說一句,您可以使用類屬性而不是全局屬性; 'connection = None' at class level,then'if not MyAddon.connection:MyAddon.connection = ...';任何* read *'self.connection'的嘗試都會找到共享類的屬性。 –

回答

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類方法異常;您需要決定如何處理數據庫配置錯誤或無法連接的情況。顯示錯誤消息是不夠的。您當然可以在仍然從__init__方法調用self.connect()來發信號通知這個問題。

+0

感謝您的模式建議。你能否向一位Python新手解釋以下留置權? cursor = .cursor() – PrashanD

+0

@Prashan:它會產生一個錯誤,因爲在編輯中我忘了在前面添加'conn'引用..對不起! –

+0

最後一件事,我注意到_connection = None在類級縮進中。你是否想要將_connection聲明爲全局變量? – PrashanD