Introduction
Imagine multiple people trying to edit the same document at the same time without any rules. Changes could get mixed up or lost. This problem also happens in databases when many users try to access or change data simultaneously.
Imagine a busy library where many people want to use the same book. The librarian makes sure only one person can take the book at a time, so pages don’t get torn or notes mixed up. This way, everyone gets the correct information without damage.
┌─────────────────────────────┐ │ Multiple Users │ │ ┌───────────────┐ │ │ │ Transaction A │ │ │ └───────────────┘ │ │ │ │ │ ↓ │ │ ┌───────────────┐ │ │ │ Concurrency │ │ │ │ Control Rules │ │ │ └───────────────┘ │ │ │ │ │ ↓ │ │ ┌───────────────┐ │ │ │ Data Updated │ │ │ │ Safely │ │ │ └───────────────┘ │ └─────────────────────────────┘
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)') # Simulate two transactions trying to update the same account conn.isolation_level = None # Manual transaction control # Transaction 1 cur.execute('BEGIN') cur.execute('SELECT balance FROM accounts WHERE id=1') balance = cur.fetchone()[0] balance += 50 # Deposit 50 cur.execute('UPDATE accounts SET balance=? WHERE id=1', (balance,)) # Transaction 2 cur2 = conn.cursor() cur2.execute('BEGIN') cur2.execute('SELECT balance FROM accounts WHERE id=1') balance2 = cur2.fetchone()[0] balance2 -= 30 # Withdraw 30 cur2.execute('UPDATE accounts SET balance=? WHERE id=1', (balance2,)) # Commit transactions cur.execute('COMMIT') cur2.execute('COMMIT') # Check final balance cur.execute('SELECT balance FROM accounts WHERE id=1') print(cur.fetchone()[0])