SQLITE_BUSY: database is locked
This error occurs when another connection is holding a lock on the database. Learn how to handle concurrent access and prevent database locking issues.
The database is locked error happens when SQLite can't acquire a lock on the database because another connection is using it. This is common in multi-threaded applications or when multiple processes access the same database.
Understanding the Error
SQLite uses file-level locking. When one connection is writing, others must wait. If the wait times out, you get this error.
SQLITE_BUSY: database is locked
Common Causes
1. Long-Running Write Transactions
A transaction that takes too long blocks other connections:
2. Uncommitted Transactions
Forgetting to commit or rollback leaves locks open:
3. Multiple Processes Accessing the Same File
Two applications or scripts accessing the same .db file simultaneously.
4. WAL Mode Not Enabled
The default journal mode is more restrictive than WAL mode.
How to Fix It
Solution 1: Enable WAL Mode
Write-Ahead Logging allows concurrent reads during writes:
This is the single most effective fix for busy errors. WAL mode allows:
- Multiple readers simultaneously
- One writer without blocking readers
- Better performance overall
Solution 2: Set a Busy Timeout
Tell SQLite to wait instead of failing immediately:
In application code:
Solution 3: Keep Transactions Short
Minimize the time locks are held:
Solution 4: Use Immediate Transactions
Start transactions with IMMEDIATE to fail fast if locked:
Solution 5: Implement Retry Logic
Retry failed operations with exponential backoff:
Solution 6: Use Connection Pooling Properly
For web applications, ensure proper connection management:
Best Practices
- Always enable WAL mode for any multi-connection use case
- Set a reasonable busy_timeout (3-10 seconds typically)
- Keep transactions as short as possible
- Always close transactions with COMMIT or ROLLBACK
- Use a single connection when possible in simple applications
- Consider a different database if you need heavy concurrent writes
Checking Current Settings
Related Errors
- SQLITE_LOCKED - Table-level lock conflict (different from BUSY)
- SQLITE_READONLY - Can't write to the database file