2016-12-06 9 views
0

私はmysqlの接続の開閉を考慮しようとしているの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 

です

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

関連する問題