What's Actually Happening

SQLite reports database is locked error when trying to write.

The Error You'll See

python
sqlite3.OperationalError: database is locked

Why This Happens

  1. 1.Connection not closed - Previous connection still open
  2. 2.Long transaction - Transaction holding lock too long
  3. 3.Multiple writers - Concurrent write attempts
  4. 4.WAL mode off - Using default journal mode

Step 1: Check Open Connections

```bash # Find processes using DB: lsof /path/to/database.db

# Check lock file: ls -la /path/to/database.db-journal ```

Step 2: Enable WAL Mode

```python import sqlite3

conn = sqlite3.connect('database.db') conn.execute('PRAGMA journal_mode=WAL') conn.execute('PRAGMA busy_timeout=5000') ```

Step 3: Proper Connection Management

```python import sqlite3 from contextlib import contextmanager

@contextmanager def get_db(): conn = sqlite3.connect('database.db', timeout=30) conn.execute('PRAGMA journal_mode=WAL') try: yield conn finally: conn.close()

# Usage: with get_db() as conn: cursor = conn.cursor() cursor.execute('INSERT INTO table VALUES (?)', (value,)) conn.commit() ```

Step 4: Handle Busy Timeout

```python # Set busy timeout: conn = sqlite3.connect('database.db', timeout=30)

# Or via PRAGMA: conn.execute('PRAGMA busy_timeout=30000') # 30 seconds ```

SQLite Locked Checklist

CheckMethodExpected
WAL modePRAGMAEnabled
Connectionscode reviewClosed
Busy timeoutPRAGMASet

Verify the Fix

python
# No database locked errors
# Writes succeed
  • [Fix SQLite Query Slow](/articles/fix-sqlite-query-slow)
  • [Fix SQLite Constraint Violation](/articles/fix-sqlite-constraint-violation)