Changed in version 2.5: if the connection is used in a with statement, commit() is automatically called if no exception is raised in the with block.
with blocks also make the code exception-safe. If an exception is thrown due to a bad query, then we rollback the transaction instead of leaving the database in a state where some queries succeeded and others failed. We also won't leak the connection and cursor, since an exception would prevent the old code from calling conn.close(). It also lets us avoid using ISOLATION_LEVEL_AUTOCOMMIT, which is not really something I'd want to steer new programmers towards using.
From the docs:
with
blocks also make the code exception-safe. If an exception is thrown due to a bad query, then we rollback the transaction instead of leaving the database in a state where some queries succeeded and others failed. We also won't leak the connection and cursor, since an exception would prevent the old code from callingconn.close()
. It also lets us avoid usingISOLATION_LEVEL_AUTOCOMMIT
, which is not really something I'd want to steer new programmers towards using.