0Pricing
Python Academy · Lesson

Transactions and Context Managers

Commit and roll back safely.

Transactions and Context Managers is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What is a Transaction?

A transaction groups several statements so they either all succeed or all fail together. This keeps your data consistent.

SQLite starts a transaction automatically before data-changing statements.

import sqlite3
conn = sqlite3.connect(':memory:')
cur = conn.cursor()
cur.execute('CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER)')
print('Table ready for transactions')
conn.close()

Commit to Save

Changes are not permanent until you call conn.commit(). Until then they exist only in the current transaction.

import sqlite3
conn = sqlite3.connect(':memory:')
cur = conn.cursor()
cur.execute('CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER)')
cur.execute('INSERT INTO accounts (balance) VALUES (100)')
conn.commit()
print('Committed')
conn.close()

Rolling Back

conn.rollback() undoes every change since the last commit. Use it when something goes wrong.

import sqlite3
conn = sqlite3.connect(':memory:')
cur = conn.cursor()
cur.execute('CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER)')
conn.commit()
cur.execute('INSERT INTO accounts (balance) VALUES (100)')
conn.rollback()
cur.execute('SELECT COUNT(*) FROM accounts')
print('Rows after rollback:', cur.fetchone()[0])
conn.close()

A Money Transfer

Transactions shine when multiple updates must stay in sync. A bank transfer subtracts from one account and adds to another. Both must happen or neither.

import sqlite3
conn = sqlite3.connect(':memory:')
cur = conn.cursor()
cur.execute('CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER)')
cur.execute('INSERT INTO accounts (id, balance) VALUES (1, 100)')
cur.execute('INSERT INTO accounts (id, balance) VALUES (2, 50)')
cur.execute('UPDATE accounts SET balance = balance - 30 WHERE id = 1')
cur.execute('UPDATE accounts SET balance = balance + 30 WHERE id = 2')
conn.commit()
cur.execute('SELECT id, balance FROM accounts')
print(cur.fetchall())
conn.close()

Handling Errors with try/except

Wrap a transaction in try/except. On error, roll back so partial changes do not corrupt your data.

import sqlite3
conn = sqlite3.connect(':memory:')
cur = conn.cursor()
cur.execute('CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER)')
try:
    cur.execute('INSERT INTO accounts (id, balance) VALUES (1, 100)')
    cur.execute('INSERT INTO accounts (id, balance) VALUES (1, 200)')
    conn.commit()
except sqlite3.IntegrityError:
    conn.rollback()
    print('Rolled back after error')
conn.close()

Connection as Context Manager

Using with conn: automatically commits on success and rolls back if an exception occurs inside the block.

import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER)')
with conn:
    conn.execute('INSERT INTO accounts (balance) VALUES (100)')
print('Auto-committed via with block')
conn.close()

Auto Rollback on Exception

If the with conn: block raises, the transaction is rolled back automatically. Note the connection itself stays open.

import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE accounts (id INTEGER PRIMARY KEY)')
try:
    with conn:
        conn.execute('INSERT INTO accounts (id) VALUES (1)')
        conn.execute('INSERT INTO accounts (id) VALUES (1)')
except sqlite3.IntegrityError:
    print('Block rolled back automatically')
count = conn.execute('SELECT COUNT(*) FROM accounts').fetchone()[0]
print('Rows:', count)
conn.close()

closing() for the Connection

The contextlib.closing helper guarantees close() is called when the block ends, freeing the connection.

import sqlite3
from contextlib import closing
with closing(sqlite3.connect(':memory:')) as conn:
    conn.execute('CREATE TABLE t (id INTEGER)')
    print('Used inside closing()')
print('Connection closed automatically')

Combining Both Patterns

Nest with conn: inside closing(...) to both manage the transaction and ensure the connection closes.

import sqlite3
from contextlib import closing
with closing(sqlite3.connect(':memory:')) as conn:
    conn.execute('CREATE TABLE t (id INTEGER, v TEXT)')
    with conn:
        conn.execute('INSERT INTO t VALUES (1, ?)', ('hello',))
    print(conn.execute('SELECT * FROM t').fetchall())

isolation_level

The connection's isolation_level controls when transactions begin. The default lets SQLite manage it; setting it to None enables autocommit mode.

import sqlite3
conn = sqlite3.connect(':memory:')
print('Default isolation_level:', repr(conn.isolation_level))
conn.isolation_level = None
print('Now autocommit:', conn.isolation_level)
conn.close()

Why Transactions Matter

Without transactions, a crash mid-update could leave half-finished data. Transactions make a set of changes atomic: indivisible. This protects integrity.

import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE log (msg TEXT)')
with conn:
    conn.execute('INSERT INTO log VALUES (?)', ('all or nothing',))
print('Atomic write done')
conn.close()

Quick Check

Test your transaction knowledge.

Recap

You learned to manage transactions safely.

  • commit() saves changes; rollback() undoes them
  • Wrap risky writes in try/except with rollback
  • with conn: auto-commits or auto-rolls-back
  • contextlib.closing guarantees the connection closes

Frequently asked questions

Is the “Transactions and Context Managers” lesson free?

Yes — the full text of “Transactions and Context Managers” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Transactions and Context Managers”?

Commit and roll back safely. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Transactions and Context Managers” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Connecting and Creating Tables
  2. Insert, Select, Update, Delete
  3. Parameterized Queries
  4. Transactions and Context Managers
← Back to Python Academy