2016-12-06 113 views
0

使用Python 2.7.9,我試圖分析出Python的MySQL和上下文管理器:__exit__屬性錯誤

的代碼是

class MySQLCursor: 
    def __init__(self, commit=False): 
     self.commit = commit 

    def __enter__(self): 
     self.conn = MySQLdb.connect(host=_MYMYSQLHOST, 
            user=_MYMYSQLUSER, 
            passwd=_MYMYSQLPASSWD, 
            db=_MYMYSQLDB) 
     self.cursor = self.conn.cursor() 
     return self.cursor 

    def __exit__(self, exc_type, exc_val, exc_tb): 
     if self.commit: 
      self.conn.commit() 
     self.cursor.close() 
     self.conn.close() 
     return 

使用它的開放和MySQL連接的關閉和遊標作爲

with MySQLCursor as cursor: 
    cursor.execute("SELECT VERSION()") 
    row = cursor.fetchone() 
    print "server version:", row[0] 

我得到錯誤信息

AttributeError: __exit__ 

這是一個MySQL問題或上下文管理器的問題?

+2

嘗試'與MySQLCursor()作爲遊標' –

回答

2

只是做with MySQLCursor() as cursor: - With語句需要具有__enter____exit__方法的類的實例,而不是類本身。

+0

有意義且有效。謝謝。 – 576i