Search code examples
pythonmysqlpython-2.7contextmanager

Python MySQL and context managers: __exit__ Attribute error


Using Python 2.7.9, I'm trying to factor out the opening and closing of mysql connections and cursors

The code is

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

using it as

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

I get the error message

AttributeError: __exit__ 

Is this a mysql problem or a context manager problem?


Solution

  • Just do with MySQLCursor() as cursor: - The With statements needs instances of classes that have the __enter__ and __exit__ methods, not the classes themselves.