bad parameter or other API misuse
SQLITE_MISUSE (result code 21) is returned when the SQLite C library detects that it is being called incorrectly — for example, using a finalised database connection, executing a statement after it has been finalised, or calling sqlite3_step() on a statement that was not properly reset. In Python, misuse scenarios are rarer because the sqlite3 module wraps the C API, but they can occur with third-party extensions.
- 1Calling methods on a closed database connection
- 2Using a connection or cursor after it has been garbage-collected in C extensions
- 3Attempting to finalise an already-finalised statement (C API)
- 4Concurrent access to a non-thread-safe connection without proper locking
A connection is closed and then a query is attempted on it.
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE t (x INTEGER)')
conn.close()
conn.execute('SELECT * FROM t') # triggers ProgrammingError (wraps SQLITE_MISUSE)expected output
sqlite3.ProgrammingError: Cannot operate on a closed database.
Fix
Use context managers to manage connection lifetime
WHEN Always — to ensure connections are properly closed and not used after close.
import sqlite3
with sqlite3.connect(':memory:') as conn:
conn.execute('CREATE TABLE t (x INTEGER)')
conn.execute('INSERT INTO t VALUES (1)')
rows = conn.execute('SELECT * FROM t').fetchall()
# conn is closed here — do not use it outside the with blockWhy this works
The context manager protocol guarantees the connection is committed (or rolled back) and closed when the with block exits, making it impossible to accidentally use a closed connection.
✕ Share a single connection object across multiple threads without locking
SQLite connections are not thread-safe by default. Concurrent use without locking is API misuse and can produce SQLITE_MISUSE or data corruption.
Python's sqlite3 module raises ProgrammingError (not OperationalError) for most SQLITE_MISUSE conditions since they represent programming errors rather than runtime failures.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev