Please elaborate on the use of `WITH` over `TRY CATCH` in this context

In general, a context manager is free to do whatever its author wants it to do when used. Set/reset a certain system state, cleaning up resources after use, acquiring/releasing a lock, etc.

In particular, as Jon already writes, a database connection object creates a transaction when used as a context manager. If you want to auto-close the connection, you can do

with contextlib.closing(sqlite3.connect(':memory:')) as conn:
    with conn as cur:
        data = cur.execute('SELECT 1, SQLITE_VERSION()').fetchone()
        print(data)  # (1, "3.39.3")

    with conn as cur:
        [[two, version]] = cur.execute('SELECT 2, SQLITE_VERSION()')
        print(two, version)  # 2 3.39.3

Leave a Comment

tech