0Pricing
Python Academy · Lesson

Transactions and Context Managers

Commit and roll back safely.

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()

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