Attributeerror:__exit__ On Python 3.4
Solution 1:
You are trying to use the connection as a context manager:
with conn:
This object doesn't implement the necessary methods to be used like that; it is not a context manager, as it is missing (at least) the __exit__
method.
If you are reading a tutorial or documentation that uses a different MySQL library, be aware that this feature may be supported by some libraries, just not this one. The MySQLdb project does support it, for example.
For your specific case, you don't even need to use the with conn:
line at all; you are not making any changes to the database, no commit is required anywhere. You can safely remove the with conn:
line (unindent everything under it one step). Otherwise you can replace the context manager with a manual conn.commit()
elsewhere.
Alternatively, you can create your own context manager for this use-case, using the @contextlib.contextmanager()
decorator:
from contextlib import contextmanager
@contextmanagerdefmanage_transaction(conn, *args, **kw):
exc = Falsetry:
try:
conn.start_transaction(*args, **kw)
yield conn.cursor()
except:
exc = True
conn.rollback()
finally:
ifnot exc:
conn.commit()
and use this as:
with manage_transaction(conn) as cursor:
# do things, including creating extra cursors
where you can pass in extra arguments for the connection.start_transaction()
call.
Post a Comment for "Attributeerror:__exit__ On Python 3.4"