docker / python-docker-dev

A simple Python app for the Python Language Guide in Docker's Docs
11 stars 32 forks source link

Use `with` blocks to manage connections, cursors, and transactions #1

Closed jthemphill closed 1 year ago

jthemphill commented 1 year ago

From the docs:

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.

craig-osterhout commented 1 year ago

Thank you. Closing. Changes applied in #2