database runtime_error ai_generated true

sqlite3.OperationalError:数据库被锁定 (背景:SQLite忙超时5000毫秒已超过)

sqlite3.OperationalError: database is locked (background: SQLite busy timeout of 5000ms exceeded)

ID: database/sqlite-busy-timeout-exceeded

其他格式: JSON · Markdown 中文 · English
85%修复率
85%置信度
1证据数
2023-11-05首次发现

版本兼容性

版本状态引入弃用备注
SQLite 3.40 active
SQLite 3.41 active
SQLite 3.42 active

根因分析

另一个连接持有写事务的时间超过忙超时时间,导致并发写入失败。

English

A write transaction is held by another connection for longer than the busy timeout, causing concurrent writes to fail.

generic

官方文档

https://www.sqlite.org/lockingv3.html

解决方案

  1. Set a higher busy timeout: PRAGMA busy_timeout = 30000; (30 seconds) to allow longer waits for locks.
  2. Switch to WAL mode: PRAGMA journal_mode=WAL; This allows concurrent reads while a write is in progress.
  3. Use a connection pool with retry logic: from sqlite3 import connect; import time; for i in range(5): try: conn.execute(...); break; except sqlite3.OperationalError: time.sleep(1)

无效尝试

常见但无效的做法:

  1. Set PRAGMA busy_timeout to 0 to disable timeout 80% 失败

    Disabling timeout causes immediate failure on lock contention, making the problem worse instead of better.

  2. Use WAL mode but keep journal_mode=DELETE 50% 失败

    WAL mode improves concurrency for readers but does not eliminate write contention; the lock still exists.