python
  • mysql
  • mariadb
  • 2015-01-15 42 views -1 likes 
    -1

    我在OS X 10.9上運行mariadb數據庫並嘗試通過python連接到它。當試圖從類內部但不是從外部獲取遊標時,獲取MySQL連接不可用

    如果我試試這個代碼,它工作得很好

    import mysql.connector as mariadb 
    
    if __name__ == "__main__": 
    
        mariadb_connection = mariadb.connect(user='root', database='account_balances') 
        cursor = mariadb_connection.cursor() 
    

    我可以將事件插入一些記錄

    但如果我嘗試

    class account(object): 
        _logging_to_db_enabled = False 
        _database_object = None 
        _database_cursor = None 
    
    def __init__(self): 
        pass 
    
    def enable_logging_to_db(self): 
        try: 
         self._database_object = mariadb.connect(mariadb.connect(user='root', database='account_balances')) 
         self._logging_to_db_enabled = True 
        except self._database_object.Error as error: 
         print ("Opening DB error: {}".format(error)) 
    
        self._database_cursor = self._database_object.cursor() 
    
    if __name__ == "__main__": 
    
        testobject = account() 
        testobject.enable_logging_to_db() 
    

    我得到這個錯誤以下

    File "....", line 22, in enable_logging_to_db 
    self._database_cursor = self._database_object.cursor() 
    File "<pathname_deleted>", line 1372, in cursor 
    raise errors.OperationalError("MySQL Connection not available.") 
    mysql.connector.errors.OperationalError: MySQL Connection not available. 
    

    An一個想法爲什麼這是主要工作,但不是在一個對象內?

    回答

    1

    因爲你有一個錯字/複製&粘貼錯誤:

    self._database_object = mariadb.connect(mariadb.connect(user='root', database='account_balances')) 
    

    它應該是:

    self._database_object = mariadb.connect(user='root', database='account_balances') 
    
    +0

    哦,天哪,(太傻非常感謝這暗示我一直在尋找一個。問題與光標。 – daeda

    相關問題