Sqlite3 error code

Many of the routines in the SQLite C-language Interface return numeric result codes indicating either success or failure, and in the event of a failure, providing some idea of the cause of the failure. This document strives to explain what each of those numeric result codes means.

Overview

Many of the routines in the SQLite C-language Interface return
numeric result codes indicating either success or failure, and
in the event of a failure, providing some idea of the cause of
the failure. This document strives to explain what each
of those numeric result codes means.

«Error codes» are a subset of «result codes» that indicate that
something has gone wrong. There are only a few non-error result
codes: SQLITE_OK, SQLITE_ROW, and SQLITE_DONE. The term
«error code» means any result code other than these three.

2. Primary Result Codes versus Extended Result Codes

Result codes are signed 32-bit integers.
The least significant 8 bits of the result code define a broad category
and are called the «primary result code». More significant bits provide
more detailed information about the error and are called the
«extended result code»

Note that the primary result code is always a part of the extended
result code. Given a full 32-bit extended result code, the application
can always find the corresponding primary result code merely by extracting
the least significant 8 bits of the extended result code.

All extended result codes are also error codes. Hence the terms
«extended result code» and «extended error code» are interchangeable.

For historic compatibility, the C-language interfaces return
primary result codes by default.
The extended result code for the most recent error can be
retrieved using the sqlite3_extended_errcode() interface.
The sqlite3_extended_result_codes() interface can be used to put
a database connection into a mode where it returns the
extended result codes instead of the primary result codes.

3. Definitions

All result codes are integers.
Symbolic names for all result codes are created using
«#define» macros in the sqlite3.h header file.
There are separate sections in the sqlite3.h header file for
the result code definitions and the extended result code definitions.

Primary result code symbolic names are of the form «SQLITE_XXXXXX» where
XXXXXX is a sequence of uppercase alphabetic characters. Extended
result code names are of the form «SQLITE_XXXXXX_YYYYYYY» where
the XXXXXX part is the corresponding primary result code and the
YYYYYYY is an extension that further classifies the result code.

The names and numeric values for existing result codes are fixed
and unchanging. However, new result codes, and especially new extended
result codes, might appear in future releases of SQLite.

4. Primary Result Code List

The 31 result codes are
defined in sqlite3.h and are listed in
alphabetical order below:

  • SQLITE_ABORT (4)
  • SQLITE_AUTH (23)
  • SQLITE_BUSY (5)
  • SQLITE_CANTOPEN (14)
  • SQLITE_CONSTRAINT (19)
  • SQLITE_CORRUPT (11)
  • SQLITE_DONE (101)
  • SQLITE_EMPTY (16)
  • SQLITE_ERROR (1)
  • SQLITE_FORMAT (24)
  • SQLITE_FULL (13)
  • SQLITE_INTERNAL (2)
  • SQLITE_INTERRUPT (9)
  • SQLITE_IOERR (10)
  • SQLITE_LOCKED (6)
  • SQLITE_MISMATCH (20)
  • SQLITE_MISUSE (21)
  • SQLITE_NOLFS (22)
  • SQLITE_NOMEM (7)
  • SQLITE_NOTADB (26)
  • SQLITE_NOTFOUND (12)
  • SQLITE_NOTICE (27)
  • SQLITE_OK (0)
  • SQLITE_PERM (3)
  • SQLITE_PROTOCOL (15)
  • SQLITE_RANGE (25)
  • SQLITE_READONLY (8)
  • SQLITE_ROW (100)
  • SQLITE_SCHEMA (17)
  • SQLITE_TOOBIG (18)
  • SQLITE_WARNING (28)

5. Extended Result Code List

The 74 extended result codes
are defined in sqlite3.h and are
listed in alphabetical order below:

  • SQLITE_ABORT_ROLLBACK (516)
  • SQLITE_AUTH_USER (279)
  • SQLITE_BUSY_RECOVERY (261)
  • SQLITE_BUSY_SNAPSHOT (517)
  • SQLITE_BUSY_TIMEOUT (773)
  • SQLITE_CANTOPEN_CONVPATH (1038)
  • SQLITE_CANTOPEN_DIRTYWAL (1294)
  • SQLITE_CANTOPEN_FULLPATH (782)
  • SQLITE_CANTOPEN_ISDIR (526)
  • SQLITE_CANTOPEN_NOTEMPDIR (270)
  • SQLITE_CANTOPEN_SYMLINK (1550)
  • SQLITE_CONSTRAINT_CHECK (275)
  • SQLITE_CONSTRAINT_COMMITHOOK (531)
  • SQLITE_CONSTRAINT_DATATYPE (3091)
  • SQLITE_CONSTRAINT_FOREIGNKEY (787)
  • SQLITE_CONSTRAINT_FUNCTION (1043)
  • SQLITE_CONSTRAINT_NOTNULL (1299)
  • SQLITE_CONSTRAINT_PINNED (2835)
  • SQLITE_CONSTRAINT_PRIMARYKEY (1555)
  • SQLITE_CONSTRAINT_ROWID (2579)
  • SQLITE_CONSTRAINT_TRIGGER (1811)
  • SQLITE_CONSTRAINT_UNIQUE (2067)
  • SQLITE_CONSTRAINT_VTAB (2323)
  • SQLITE_CORRUPT_INDEX (779)
  • SQLITE_CORRUPT_SEQUENCE (523)
  • SQLITE_CORRUPT_VTAB (267)
  • SQLITE_ERROR_MISSING_COLLSEQ (257)
  • SQLITE_ERROR_RETRY (513)
  • SQLITE_ERROR_SNAPSHOT (769)
  • SQLITE_IOERR_ACCESS (3338)
  • SQLITE_IOERR_AUTH (7178)
  • SQLITE_IOERR_BEGIN_ATOMIC (7434)
  • SQLITE_IOERR_BLOCKED (2826)
  • SQLITE_IOERR_CHECKRESERVEDLOCK (3594)
  • SQLITE_IOERR_CLOSE (4106)
  • SQLITE_IOERR_COMMIT_ATOMIC (7690)
  • SQLITE_IOERR_CONVPATH (6666)
  • SQLITE_IOERR_CORRUPTFS (8458)
  • SQLITE_IOERR_DATA (8202)
  • SQLITE_IOERR_DELETE (2570)
  • SQLITE_IOERR_DELETE_NOENT (5898)
  • SQLITE_IOERR_DIR_CLOSE (4362)
  • SQLITE_IOERR_DIR_FSYNC (1290)
  • SQLITE_IOERR_FSTAT (1802)
  • SQLITE_IOERR_FSYNC (1034)
  • SQLITE_IOERR_GETTEMPPATH (6410)
  • SQLITE_IOERR_LOCK (3850)
  • SQLITE_IOERR_MMAP (6154)
  • SQLITE_IOERR_NOMEM (3082)
  • SQLITE_IOERR_RDLOCK (2314)
  • SQLITE_IOERR_READ (266)
  • SQLITE_IOERR_ROLLBACK_ATOMIC (7946)
  • SQLITE_IOERR_SEEK (5642)
  • SQLITE_IOERR_SHMLOCK (5130)
  • SQLITE_IOERR_SHMMAP (5386)
  • SQLITE_IOERR_SHMOPEN (4618)
  • SQLITE_IOERR_SHMSIZE (4874)
  • SQLITE_IOERR_SHORT_READ (522)
  • SQLITE_IOERR_TRUNCATE (1546)
  • SQLITE_IOERR_UNLOCK (2058)
  • SQLITE_IOERR_VNODE (6922)
  • SQLITE_IOERR_WRITE (778)
  • SQLITE_LOCKED_SHAREDCACHE (262)
  • SQLITE_LOCKED_VTAB (518)
  • SQLITE_NOTICE_RECOVER_ROLLBACK (539)
  • SQLITE_NOTICE_RECOVER_WAL (283)
  • SQLITE_OK_LOAD_PERMANENTLY (256)
  • SQLITE_READONLY_CANTINIT (1288)
  • SQLITE_READONLY_CANTLOCK (520)
  • SQLITE_READONLY_DBMOVED (1032)
  • SQLITE_READONLY_DIRECTORY (1544)
  • SQLITE_READONLY_RECOVERY (264)
  • SQLITE_READONLY_ROLLBACK (776)
  • SQLITE_WARNING_AUTOINDEX (284)

6. Result Code Meanings

The meanings for all 105
result code values are shown below,
in numeric order.

(0) SQLITE_OK

The SQLITE_OK result code means that the operation was successful and
that there were no errors. Most other result codes indicate an error.

(1) SQLITE_ERROR

The SQLITE_ERROR result code is a generic error code that is used when
no other more specific error code is available.

(2) SQLITE_INTERNAL

The SQLITE_INTERNAL result code indicates an internal malfunction.
In a working version of SQLite, an application should never see this
result code. If application does encounter this result code, it shows
that there is a bug in the database engine.

SQLite does not currently generate this result code.
However, application-defined SQL functions or
virtual tables, or VFSes, or other extensions might cause this
result code to be returned.

(3) SQLITE_PERM

The SQLITE_PERM result code indicates that the requested access mode
for a newly created database could not be provided.

(4) SQLITE_ABORT

The SQLITE_ABORT result code indicates that an operation was aborted
prior to completion, usually be application request.
See also: SQLITE_INTERRUPT.

If the callback function to sqlite3_exec() returns non-zero, then
sqlite3_exec() will return SQLITE_ABORT.

If a ROLLBACK operation occurs on the same database connection as
a pending read or write, then the pending read or write may fail with
an SQLITE_ABORT or SQLITE_ABORT_ROLLBACK error.

In addition to being a result code,
the SQLITE_ABORT value is also used as a conflict resolution mode
returned from the sqlite3_vtab_on_conflict() interface.

(5) SQLITE_BUSY

The SQLITE_BUSY result code indicates that the database file could not
be written (or in some cases read) because of concurrent activity by
some other database connection, usually a database connection in a
separate process.

For example, if process A is in the middle of a large write transaction
and at the same time process B attempts to start a new write transaction,
process B will get back an SQLITE_BUSY result because SQLite only supports
one writer at a time. Process B will need to wait for process A to finish
its transaction before starting a new transaction. The
sqlite3_busy_timeout() and sqlite3_busy_handler() interfaces and
the busy_timeout pragma are available to process B to help it deal
with SQLITE_BUSY errors.

An SQLITE_BUSY error can occur at any point in a transaction: when the
transaction is first started, during any write or update operations, or
when the transaction commits.
To avoid encountering SQLITE_BUSY errors in the middle of a transaction,
the application can use BEGIN IMMEDIATE instead of just BEGIN to
start a transaction. The BEGIN IMMEDIATE command might itself return
SQLITE_BUSY, but if it succeeds, then SQLite guarantees that no
subsequent operations on the same database through the next COMMIT
will return SQLITE_BUSY.

See also: SQLITE_BUSY_RECOVERY and SQLITE_BUSY_SNAPSHOT.

The SQLITE_BUSY result code differs from SQLITE_LOCKED in that
SQLITE_BUSY indicates a conflict with a
separate database connection, probably in a separate process,
whereas SQLITE_LOCKED
indicates a conflict within the same database connection (or sometimes
a database connection with a shared cache).

(6) SQLITE_LOCKED

The SQLITE_LOCKED result code indicates that a write operation could not
continue because of a conflict within the same database connection or
a conflict with a different database connection that uses a shared cache.

For example, a DROP TABLE statement cannot be run while another thread
is reading from that table on the same database connection because
dropping the table would delete the table out from under the concurrent
reader.

The SQLITE_LOCKED result code differs from SQLITE_BUSY in that
SQLITE_LOCKED indicates a conflict on the same database connection
(or on a connection with a shared cache) whereas SQLITE_BUSY indicates
a conflict with a different database connection, probably in a different
process.

(7) SQLITE_NOMEM

The SQLITE_NOMEM result code indicates that SQLite was unable to allocate
all the memory it needed to complete the operation. In other words, an
internal call to sqlite3_malloc() or sqlite3_realloc() has failed in
a case where the memory being allocated was required in order to continue
the operation.

(8) SQLITE_READONLY

The SQLITE_READONLY result code is returned when an attempt is made to
alter some data for which the current database connection does not have
write permission.

(9) SQLITE_INTERRUPT

The SQLITE_INTERRUPT result code indicates that an operation was
interrupted by the sqlite3_interrupt() interface.
See also: SQLITE_ABORT

(10) SQLITE_IOERR

The SQLITE_IOERR result code says that the operation could not finish
because the operating system reported an I/O error.

A full disk drive will normally give an SQLITE_FULL error rather than
an SQLITE_IOERR error.

There are many different extended result codes for I/O errors that
identify the specific I/O operation that failed.

(11) SQLITE_CORRUPT

The SQLITE_CORRUPT result code indicates that the database file has
been corrupted. See the How To Corrupt Your Database Files for
further discussion on how corruption can occur.

(12) SQLITE_NOTFOUND

The SQLITE_NOTFOUND result code is exposed in three ways:

  1. SQLITE_NOTFOUND can be returned by the sqlite3_file_control() interface
    to indicate that the file control opcode passed as the third argument
    was not recognized by the underlying VFS.

  2. SQLITE_NOTFOUND can also be returned by the xSetSystemCall() method of
    an sqlite3_vfs object.

  3. SQLITE_NOTFOUND an be returned by sqlite3_vtab_rhs_value() to indicate
    that the right-hand operand of a constraint is not available to the
    xBestIndex method that made the call.

The SQLITE_NOTFOUND result code is also used
internally by the SQLite implementation, but those internal uses are
not exposed to the application.

(13) SQLITE_FULL

The SQLITE_FULL result code indicates that a write could not complete
because the disk is full. Note that this error can occur when trying
to write information into the main database file, or it can also
occur when writing into temporary disk files.

Sometimes applications encounter this error even though there is an
abundance of primary disk space because the error occurs when writing
into temporary disk files on a system where temporary files are stored
on a separate partition with much less space that the primary disk.

(14) SQLITE_CANTOPEN

The SQLITE_CANTOPEN result code indicates that SQLite was unable to
open a file. The file in question might be a primary database file
or one of several temporary disk files.

(15) SQLITE_PROTOCOL

The SQLITE_PROTOCOL result code indicates a problem with the file locking
protocol used by SQLite. The SQLITE_PROTOCOL error is currently only
returned when using WAL mode and attempting to start a new transaction.
There is a race condition that can occur when two separate
database connections both try to start a transaction at the same time
in WAL mode. The loser of the race backs off and tries again, after
a brief delay. If the same connection loses the locking race dozens
of times over a span of multiple seconds, it will eventually give up and
return SQLITE_PROTOCOL. The SQLITE_PROTOCOL error should appear in practice
very, very rarely, and only when there are many separate processes all
competing intensely to write to the same database.

(16) SQLITE_EMPTY

The SQLITE_EMPTY result code is not currently used.

(17) SQLITE_SCHEMA

The SQLITE_SCHEMA result code indicates that the database schema
has changed. This result code can be returned from sqlite3_step() for
a prepared statement that was generated using sqlite3_prepare() or
sqlite3_prepare16(). If the database schema was changed by some other
process in between the time that the statement was prepared and the time
the statement was run, this error can result.

If a prepared statement is generated from sqlite3_prepare_v2() then
the statement is automatically re-prepared if the schema changes, up to
SQLITE_MAX_SCHEMA_RETRY times (default: 50). The sqlite3_step()
interface will only return SQLITE_SCHEMA back to the application if
the failure persists after these many retries.

(18) SQLITE_TOOBIG

The SQLITE_TOOBIG error code indicates that a string or BLOB was
too large. The default maximum length of a string or BLOB in SQLite is
1,000,000,000 bytes. This maximum length can be changed at compile-time
using the SQLITE_MAX_LENGTH compile-time option, or at run-time using
the sqlite3_limit(db,SQLITE_LIMIT_LENGTH,…) interface. The
SQLITE_TOOBIG error results when SQLite encounters a string or BLOB
that exceeds the compile-time or run-time limit.

The SQLITE_TOOBIG error code can also result when an oversized SQL
statement is passed into one of the sqlite3_prepare_v2() interfaces.
The maximum length of an SQL statement defaults to a much smaller
value of 1,000,000,000 bytes. The maximum SQL statement length can be
set at compile-time using SQLITE_MAX_SQL_LENGTH or at run-time
using sqlite3_limit(db,SQLITE_LIMIT_SQL_LENGTH,…).

(19) SQLITE_CONSTRAINT

The SQLITE_CONSTRAINT error code means that an SQL constraint violation
occurred while trying to process an SQL statement. Additional information
about the failed constraint can be found by consulting the
accompanying error message (returned via sqlite3_errmsg() or
sqlite3_errmsg16()) or by looking at the extended error code.

The SQLITE_CONSTRAINT code can also be used as the return value from
the xBestIndex() method of a virtual table implementation. When
xBestIndex() returns SQLITE_CONSTRAINT, that indicates that the particular
combination of inputs submitted to xBestIndex() cannot result in a
usable query plan and should not be given further consideration.

(20) SQLITE_MISMATCH

The SQLITE_MISMATCH error code indicates a datatype mismatch.

SQLite is normally very forgiving about mismatches between the type of
a value and the declared type of the container in which that value is
to be stored. For example, SQLite allows the application to store
a large BLOB in a column with a declared type of BOOLEAN. But in a few
cases, SQLite is strict about types. The SQLITE_MISMATCH error is
returned in those few cases when the types do not match.

The rowid of a table must be an integer. Attempt to set the rowid
to anything other than an integer (or a NULL which will be automatically
converted into the next available integer rowid) results in an
SQLITE_MISMATCH error.

(21) SQLITE_MISUSE

The SQLITE_MISUSE return code might be returned if the application uses
any SQLite interface in a way that is undefined or unsupported. For
example, using a prepared statement after that prepared statement has
been finalized might result in an SQLITE_MISUSE error.

SQLite tries to detect misuse and report the misuse using this result code.
However, there is no guarantee that the detection of misuse will be
successful. Misuse detection is probabilistic. Applications should
never depend on an SQLITE_MISUSE return value.

If SQLite ever returns SQLITE_MISUSE from any interface, that means that
the application is incorrectly coded and needs to be fixed. Do not ship
an application that sometimes returns SQLITE_MISUSE from a standard
SQLite interface because that application contains potentially serious bugs.

(22) SQLITE_NOLFS

The SQLITE_NOLFS error can be returned on systems that do not support
large files when the database grows to be larger than what the filesystem
can handle. «NOLFS» stands for «NO Large File Support».

(23) SQLITE_AUTH

The SQLITE_AUTH error is returned when the
authorizer callback indicates that an
SQL statement being prepared is not authorized.

(24) SQLITE_FORMAT

The SQLITE_FORMAT error code is not currently used by SQLite.

(25) SQLITE_RANGE

The SQLITE_RANGE error indices that the parameter number argument
to one of the sqlite3_bind routines or the
column number in one of the sqlite3_column
routines is out of range.

(26) SQLITE_NOTADB

When attempting to open a file, the SQLITE_NOTADB error indicates that
the file being opened does not appear to be an SQLite database file.

(27) SQLITE_NOTICE

The SQLITE_NOTICE result code is not returned by any C/C++ interface.
However, SQLITE_NOTICE (or rather one of its extended error codes)
is sometimes used as the first argument in an sqlite3_log() callback
to indicate that an unusual operation is taking place.

(28) SQLITE_WARNING

The SQLITE_WARNING result code is not returned by any C/C++ interface.
However, SQLITE_WARNING (or rather one of its extended error codes)
is sometimes used as the first argument in an sqlite3_log() callback
to indicate that an unusual and possibly ill-advised operation is
taking place.

(100) SQLITE_ROW

The SQLITE_ROW result code returned by
sqlite3_step() indicates that another row of output is available.

(101) SQLITE_DONE

The SQLITE_DONE result code indicates that an operation has completed.
The SQLITE_DONE result code is most commonly seen as a return value
from sqlite3_step() indicating that the SQL statement has run to
completion. But SQLITE_DONE can also be returned by other multi-step
interfaces such as sqlite3_backup_step().

(256) SQLITE_OK_LOAD_PERMANENTLY

The sqlite3_load_extension() interface loads an
extension into a single
database connection. The default behavior is for that extension to be
automatically unloaded when the database connection closes. However,
if the extension entry point returns SQLITE_OK_LOAD_PERMANENTLY instead
of SQLITE_OK, then the extension remains loaded into the process address
space after the database connection closes. In other words, the
xDlClose methods of the sqlite3_vfs object is not called for the
extension when the database connection closes.

The SQLITE_OK_LOAD_PERMANENTLY return code is useful to
loadable extensions that register new VFSes, for example.

(257) SQLITE_ERROR_MISSING_COLLSEQ

The SQLITE_ERROR_MISSING_COLLSEQ result code means that an SQL
statement could not be prepared because a collating sequence named
in that SQL statement could not be located.

Sometimes when this error code is encountered, the
sqlite3_prepare_v2() routine will convert the error into
SQLITE_ERROR_RETRY and try again to prepare the SQL statement
using a different query plan that does not require the use of
the unknown collating sequence.

(261) SQLITE_BUSY_RECOVERY

The SQLITE_BUSY_RECOVERY error code is an extended error code
for SQLITE_BUSY that indicates that an operation could not continue
because another process is busy recovering a WAL mode database file
following a crash. The SQLITE_BUSY_RECOVERY error code only occurs
on WAL mode databases.

(262) SQLITE_LOCKED_SHAREDCACHE

The SQLITE_LOCKED_SHAREDCACHE result code indicates that access to
an SQLite data record is blocked by another database connection that
is using the same record in shared cache mode. When two or more
database connections share the same cache and one of the connections is
in the middle of modifying a record in that cache, then other connections
are blocked from accessing that data while the modifications are on-going
in order to prevent the readers from seeing a corrupt or partially
completed change.

(264) SQLITE_READONLY_RECOVERY

The SQLITE_READONLY_RECOVERY error code is an extended error code
for SQLITE_READONLY. The SQLITE_READONLY_RECOVERY error code indicates
that a WAL mode database cannot be opened because the database file
needs to be recovered and recovery requires write access but only
read access is available.

(266) SQLITE_IOERR_READ

The SQLITE_IOERR_READ error code is an extended error code
for SQLITE_IOERR indicating an I/O error in the VFS layer
while trying to read from a file on disk. This error might result
from a hardware malfunction or because a filesystem came unmounted
while the file was open.

(267) SQLITE_CORRUPT_VTAB

The SQLITE_CORRUPT_VTAB error code is an extended error code
for SQLITE_CORRUPT used by virtual tables. A virtual table might
return SQLITE_CORRUPT_VTAB to indicate that content in the virtual table
is corrupt.

(270) SQLITE_CANTOPEN_NOTEMPDIR

The SQLITE_CANTOPEN_NOTEMPDIR error code is no longer used.

(275) SQLITE_CONSTRAINT_CHECK

The SQLITE_CONSTRAINT_CHECK error code is an extended error code
for SQLITE_CONSTRAINT indicating that a CHECK constraint failed.

(279) SQLITE_AUTH_USER

The SQLITE_AUTH_USER error code is an extended error code
for SQLITE_AUTH indicating that an operation was attempted on a
database for which the logged in user lacks sufficient authorization.

(283) SQLITE_NOTICE_RECOVER_WAL

The SQLITE_NOTICE_RECOVER_WAL result code is
passed to the callback of
sqlite3_log() when a WAL mode database file is recovered.

(284) SQLITE_WARNING_AUTOINDEX

The SQLITE_WARNING_AUTOINDEX result code is
passed to the callback of
sqlite3_log() whenever automatic indexing is used.
This can serve as a warning to application designers that the
database might benefit from additional indexes.

(513) SQLITE_ERROR_RETRY

The SQLITE_ERROR_RETRY is used internally to provoke sqlite3_prepare_v2()
(or one of its sibling routines for creating prepared statements) to
try again to prepare a statement that failed with an error on the
previous attempt.

(516) SQLITE_ABORT_ROLLBACK

The SQLITE_ABORT_ROLLBACK error code is an extended error code
for SQLITE_ABORT indicating that an SQL statement aborted because
the transaction that was active when the SQL statement first started
was rolled back. Pending write operations always fail with this error
when a rollback occurs. A ROLLBACK will cause a pending read operation
to fail only if the schema was changed within the transaction being rolled
back.

(517) SQLITE_BUSY_SNAPSHOT

The SQLITE_BUSY_SNAPSHOT error code is an extended error code
for SQLITE_BUSY that occurs on WAL mode databases when a database
connection tries to promote a read transaction into a write transaction
but finds that another database connection has already written to the
database and thus invalidated prior reads.

The following scenario illustrates how an SQLITE_BUSY_SNAPSHOT error
might arise:

  1. Process A starts a read transaction on the database and does one
    or more SELECT statement. Process A keeps the transaction open.
  2. Process B updates the database, changing values previous read by
    process A.
  3. Process A now tries to write to the database. But process A’s view
    of the database content is now obsolete because process B has
    modified the database file after process A read from it. Hence
    process A gets an SQLITE_BUSY_SNAPSHOT error.

(518) SQLITE_LOCKED_VTAB

The SQLITE_LOCKED_VTAB result code is not used by the SQLite core, but
it is available for use by extensions. Virtual table implementations
can return this result code to indicate that they cannot complete the
current operation because of locks held by other threads or processes.

The R-Tree extension returns this result code when an attempt is made
to update the R-Tree while another prepared statement is actively reading
the R-Tree. The update cannot proceed because any change to an R-Tree
might involve reshuffling and rebalancing of nodes, which would disrupt
read cursors, causing some rows to be repeated and other rows to be
omitted.

(520) SQLITE_READONLY_CANTLOCK

The SQLITE_READONLY_CANTLOCK error code is an extended error code
for SQLITE_READONLY. The SQLITE_READONLY_CANTLOCK error code indicates
that SQLite is unable to obtain a read lock on a WAL mode database
because the shared-memory file associated with that database is read-only.

(522) SQLITE_IOERR_SHORT_READ

The SQLITE_IOERR_SHORT_READ error code is an extended error code
for SQLITE_IOERR indicating that a read attempt in the VFS layer
was unable to obtain as many bytes as was requested. This might be
due to a truncated file.

(523) SQLITE_CORRUPT_SEQUENCE

The SQLITE_CORRUPT_SEQUENCE result code means that the schema of
the sqlite_sequence table is corrupt. The sqlite_sequence table
is used to help implement the AUTOINCREMENT feature. The
sqlite_sequence table should have the following format:

  CREATE TABLE sqlite_sequence(name,seq);
  

If SQLite discovers that the sqlite_sequence table has any other
format, it returns the SQLITE_CORRUPT_SEQUENCE error.

(526) SQLITE_CANTOPEN_ISDIR

The SQLITE_CANTOPEN_ISDIR error code is an extended error code
for SQLITE_CANTOPEN indicating that a file open operation failed because
the file is really a directory.

(531) SQLITE_CONSTRAINT_COMMITHOOK

The SQLITE_CONSTRAINT_COMMITHOOK error code
is an extended error code
for SQLITE_CONSTRAINT indicating that a
commit hook callback returned non-zero that thus
caused the SQL statement to be rolled back.

(539) SQLITE_NOTICE_RECOVER_ROLLBACK

The SQLITE_NOTICE_RECOVER_ROLLBACK result code is
passed to the callback of
sqlite3_log() when a hot journal is rolled back.

(769) SQLITE_ERROR_SNAPSHOT

The SQLITE_ERROR_SNAPSHOT result code might be returned when attempting
to start a read transaction on an historical version of the database
by using the sqlite3_snapshot_open() interface. If the historical
snapshot is no longer available, then the read transaction will fail
with the SQLITE_ERROR_SNAPSHOT. This error code is only possible if
SQLite is compiled with -DSQLITE_ENABLE_SNAPSHOT.

(773) SQLITE_BUSY_TIMEOUT

The SQLITE_BUSY_TIMEOUT error code indicates that a blocking Posix
advisory file lock request in the VFS layer failed due to a timeout.
Blocking Posix advisory locks are only
available as a proprietary SQLite extension and even then are only
supported if SQLite is compiled with the SQLITE_EANBLE_SETLK_TIMEOUT
compile-time option.

(776) SQLITE_READONLY_ROLLBACK

The SQLITE_READONLY_ROLLBACK error code is an extended error code
for SQLITE_READONLY. The SQLITE_READONLY_ROLLBACK error code indicates
that a database cannot be opened because it has a hot journal that
needs to be rolled back but cannot because the database is readonly.

(778) SQLITE_IOERR_WRITE

The SQLITE_IOERR_WRITE error code is an extended error code
for SQLITE_IOERR indicating an I/O error in the VFS layer
while trying to write into a file on disk. This error might result
from a hardware malfunction or because a filesystem came unmounted
while the file was open. This error should not occur if the filesystem
is full as there is a separate error code (SQLITE_FULL) for that purpose.

(779) SQLITE_CORRUPT_INDEX

The SQLITE_CORRUPT_INDEX result code means that SQLite detected
an entry is or was missing from an index. This is a special case of
the SQLITE_CORRUPT error code that suggests that the problem might
be resolved by running the REINDEX command, assuming no other
problems exist elsewhere in the database file.

(782) SQLITE_CANTOPEN_FULLPATH

The SQLITE_CANTOPEN_FULLPATH error code is an extended error code
for SQLITE_CANTOPEN indicating that a file open operation failed because
the operating system was unable to convert the filename into a full pathname.

(787) SQLITE_CONSTRAINT_FOREIGNKEY

The SQLITE_CONSTRAINT_FOREIGNKEY error code
is an extended error code
for SQLITE_CONSTRAINT indicating that a foreign key constraint failed.

(1032) SQLITE_READONLY_DBMOVED

The SQLITE_READONLY_DBMOVED error code is an extended error code
for SQLITE_READONLY. The SQLITE_READONLY_DBMOVED error code indicates
that a database cannot be modified because the database file has been
moved since it was opened, and so any attempt to modify the database
might result in database corruption if the processes crashes because the
rollback journal would not be correctly named.

(1034) SQLITE_IOERR_FSYNC

The SQLITE_IOERR_FSYNC error code is an extended error code
for SQLITE_IOERR indicating an I/O error in the VFS layer
while trying to flush previously written content out of OS and/or
disk-control buffers and into persistent storage. In other words,
this code indicates a problem with the fsync() system call in unix
or the FlushFileBuffers() system call in windows.

(1038) SQLITE_CANTOPEN_CONVPATH

The SQLITE_CANTOPEN_CONVPATH error code is an extended error code
for SQLITE_CANTOPEN used only by Cygwin VFS and indicating that
the cygwin_conv_path() system call failed while trying to open a file.
See also: SQLITE_IOERR_CONVPATH

(1043) SQLITE_CONSTRAINT_FUNCTION

The SQLITE_CONSTRAINT_FUNCTION error code is not currently used
by the SQLite core. However, this error code is available for use
by extension functions.

(1288) SQLITE_READONLY_CANTINIT

The SQLITE_READONLY_CANTINIT result code originates in the xShmMap method
of a VFS to indicate that the shared memory region used by WAL mode
exists buts its content is unreliable and unusable by the current process
since the current process does not have write permission on the shared
memory region. (The shared memory region for WAL mode is normally a
file with a «-wal» suffix that is mmapped into the process space. If
the current process does not have write permission on that file, then it
cannot write into shared memory.)

Higher level logic within SQLite will normally intercept the error code
and create a temporary in-memory shared memory region so that the current
process can at least read the content of the database. This result code
should not reach the application interface layer.

(1290) SQLITE_IOERR_DIR_FSYNC

The SQLITE_IOERR_DIR_FSYNC error code is an extended error code
for SQLITE_IOERR indicating an I/O error in the VFS layer
while trying to invoke fsync() on a directory. The unix VFS attempts
to fsync() directories after creating or deleting certain files to
ensure that those files will still appear in the filesystem following
a power loss or system crash. This error code indicates a problem
attempting to perform that fsync().

(1294) SQLITE_CANTOPEN_DIRTYWAL

The SQLITE_CANTOPEN_DIRTYWAL result code is not used at this time.

(1299) SQLITE_CONSTRAINT_NOTNULL

The SQLITE_CONSTRAINT_NOTNULL error code
is an extended error code
for SQLITE_CONSTRAINT indicating that a NOT NULL constraint failed.

(1544) SQLITE_READONLY_DIRECTORY

The SQLITE_READONLY_DIRECTORY result code indicates that the database
is read-only because process does not have permission to create
a journal file in the same directory as the database and the creation of
a journal file is a prerequisite for writing.

(1546) SQLITE_IOERR_TRUNCATE

The SQLITE_IOERR_TRUNCATE error code is an extended error code
for SQLITE_IOERR indicating an I/O error in the VFS layer
while trying to truncate a file to a smaller size.

(1550) SQLITE_CANTOPEN_SYMLINK

The SQLITE_CANTOPEN_SYMLINK result code is returned by the
sqlite3_open() interface and its siblings when the
SQLITE_OPEN_NOFOLLOW flag is used and the database file is
a symbolic link.

(1555) SQLITE_CONSTRAINT_PRIMARYKEY

The SQLITE_CONSTRAINT_PRIMARYKEY error code
is an extended error code
for SQLITE_CONSTRAINT indicating that a PRIMARY KEY constraint failed.

(1802) SQLITE_IOERR_FSTAT

The SQLITE_IOERR_FSTAT error code is an extended error code
for SQLITE_IOERR indicating an I/O error in the VFS layer
while trying to invoke fstat() (or the equivalent) on a file in order
to determine information such as the file size or access permissions.

(1811) SQLITE_CONSTRAINT_TRIGGER

The SQLITE_CONSTRAINT_TRIGGER error code
is an extended error code
for SQLITE_CONSTRAINT indicating that a RAISE function within
a trigger fired, causing the SQL statement to abort.

(2058) SQLITE_IOERR_UNLOCK

The SQLITE_IOERR_UNLOCK error code is an extended error code
for SQLITE_IOERR indicating an I/O error
within xUnlock method on the sqlite3_io_methods object.

(2067) SQLITE_CONSTRAINT_UNIQUE

The SQLITE_CONSTRAINT_UNIQUE error code
is an extended error code
for SQLITE_CONSTRAINT indicating that a UNIQUE constraint failed.

(2314) SQLITE_IOERR_RDLOCK

The SQLITE_IOERR_UNLOCK error code is an extended error code
for SQLITE_IOERR indicating an I/O error
within xLock method on the sqlite3_io_methods object while trying
to obtain a read lock.

(2323) SQLITE_CONSTRAINT_VTAB

The SQLITE_CONSTRAINT_VTAB error code is not currently used
by the SQLite core. However, this error code is available for use
by application-defined virtual tables.

(2570) SQLITE_IOERR_DELETE

The SQLITE_IOERR_UNLOCK error code is an extended error code
for SQLITE_IOERR indicating an I/O error
within xDelete method on the sqlite3_vfs object.

(2579) SQLITE_CONSTRAINT_ROWID

The SQLITE_CONSTRAINT_ROWID error code
is an extended error code
for SQLITE_CONSTRAINT indicating that a rowid is not unique.

(2826) SQLITE_IOERR_BLOCKED

The SQLITE_IOERR_BLOCKED error code is no longer used.

(2835) SQLITE_CONSTRAINT_PINNED

The SQLITE_CONSTRAINT_PINNED error code
is an extended error code
for SQLITE_CONSTRAINT indicating that an UPDATE trigger attempted
do delete the row that was being updated in the middle of the update.

(3082) SQLITE_IOERR_NOMEM

The SQLITE_IOERR_NOMEM error code is sometimes returned by the VFS
layer to indicate that an operation could not be completed due to the
inability to allocate sufficient memory. This error code is normally
converted into SQLITE_NOMEM by the higher layers of SQLite before
being returned to the application.

(3091) SQLITE_CONSTRAINT_DATATYPE

The SQLITE_CONSTRAINT_DATATYPE error code
is an extended error code
for SQLITE_CONSTRAINT indicating that an insert or update attempted
to store a value inconsistent with the column’s declared type
in a table defined as STRICT.

(3338) SQLITE_IOERR_ACCESS

The SQLITE_IOERR_ACCESS error code is an extended error code
for SQLITE_IOERR indicating an I/O error
within the xAccess method on the sqlite3_vfs object.

(3594) SQLITE_IOERR_CHECKRESERVEDLOCK

The SQLITE_IOERR_CHECKRESERVEDLOCK error code is
an extended error code
for SQLITE_IOERR indicating an I/O error
within the xCheckReservedLock method on the sqlite3_io_methods object.

(3850) SQLITE_IOERR_LOCK

The SQLITE_IOERR_LOCK error code is an extended error code
for SQLITE_IOERR indicating an I/O error in the
advisory file locking logic.
Usually an SQLITE_IOERR_LOCK error indicates a problem obtaining
a PENDING lock. However it can also indicate miscellaneous
locking errors on some of the specialized VFSes used on Macs.

(4106) SQLITE_IOERR_CLOSE

The SQLITE_IOERR_ACCESS error code is an extended error code
for SQLITE_IOERR indicating an I/O error
within the xClose method on the sqlite3_io_methods object.

(4362) SQLITE_IOERR_DIR_CLOSE

The SQLITE_IOERR_DIR_CLOSE error code is no longer used.

(4618) SQLITE_IOERR_SHMOPEN

The SQLITE_IOERR_SHMOPEN error code is an extended error code
for SQLITE_IOERR indicating an I/O error
within the xShmMap method on the sqlite3_io_methods object
while trying to open a new shared memory segment.

(4874) SQLITE_IOERR_SHMSIZE

The SQLITE_IOERR_SHMSIZE error code is an extended error code
for SQLITE_IOERR indicating an I/O error
within the xShmMap method on the sqlite3_io_methods object
while trying to enlarge a «shm» file as part of
WAL mode transaction processing. This error may indicate that
the underlying filesystem volume is out of space.

(5130) SQLITE_IOERR_SHMLOCK

The SQLITE_IOERR_SHMLOCK error code is no longer used.

(5386) SQLITE_IOERR_SHMMAP

The SQLITE_IOERR_SHMMAP error code is an extended error code
for SQLITE_IOERR indicating an I/O error
within the xShmMap method on the sqlite3_io_methods object
while trying to map a shared memory segment into the process address space.

(5642) SQLITE_IOERR_SEEK

The SQLITE_IOERR_SEEK error code is an extended error code
for SQLITE_IOERR indicating an I/O error
within the xRead or xWrite methods on the sqlite3_io_methods object
while trying to seek a file descriptor to the beginning point of the
file where the read or write is to occur.

(5898) SQLITE_IOERR_DELETE_NOENT

The SQLITE_IOERR_DELETE_NOENT error code
is an extended error code
for SQLITE_IOERR indicating that the
xDelete method on the sqlite3_vfs object failed because the
file being deleted does not exist.

(6154) SQLITE_IOERR_MMAP

The SQLITE_IOERR_MMAP error code is an extended error code
for SQLITE_IOERR indicating an I/O error
within the xFetch or xUnfetch methods on the sqlite3_io_methods object
while trying to map or unmap part of the database file into the
process address space.

(6410) SQLITE_IOERR_GETTEMPPATH

The SQLITE_IOERR_GETTEMPPATH error code is an extended error code
for SQLITE_IOERR indicating that the VFS is unable to determine
a suitable directory in which to place temporary files.

(6666) SQLITE_IOERR_CONVPATH

The SQLITE_IOERR_CONVPATH error code is an extended error code
for SQLITE_IOERR used only by Cygwin VFS and indicating that
the cygwin_conv_path() system call failed.
See also: SQLITE_CANTOPEN_CONVPATH

(6922) SQLITE_IOERR_VNODE

The SQLITE_IOERR_VNODE error code is a code reserved for use
by extensions. It is not used by the SQLite core.

(7178) SQLITE_IOERR_AUTH

The SQLITE_IOERR_AUTH error code is a code reserved for use
by extensions. It is not used by the SQLite core.

(7434) SQLITE_IOERR_BEGIN_ATOMIC

The SQLITE_IOERR_BEGIN_ATOMIC error code indicates that the
underlying operating system reported and error on the
SQLITE_FCNTL_BEGIN_ATOMIC_WRITE file-control. This only comes
up when SQLITE_ENABLE_ATOMIC_WRITE is enabled and the database
is hosted on a filesystem that supports atomic writes.

(7690) SQLITE_IOERR_COMMIT_ATOMIC

The SQLITE_IOERR_COMMIT_ATOMIC error code indicates that the
underlying operating system reported and error on the
SQLITE_FCNTL_COMMIT_ATOMIC_WRITE file-control. This only comes
up when SQLITE_ENABLE_ATOMIC_WRITE is enabled and the database
is hosted on a filesystem that supports atomic writes.

(7946) SQLITE_IOERR_ROLLBACK_ATOMIC

The SQLITE_IOERR_ROLLBACK_ATOMIC error code indicates that the
underlying operating system reported and error on the
SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE file-control. This only comes
up when SQLITE_ENABLE_ATOMIC_WRITE is enabled and the database
is hosted on a filesystem that supports atomic writes.

(8202) SQLITE_IOERR_DATA

The SQLITE_IOERR_DATA error code is an extended error code
for SQLITE_IOERR used only by checksum VFS shim to indicate that
the checksum on a page of the database file is incorrect.

(8458) SQLITE_IOERR_CORRUPTFS

The SQLITE_IOERR_CORRUPTFS error code is an extended error code
for SQLITE_IOERR used only by a VFS to indicate that a seek or read
failure was due to the request not falling within the file’s boundary
rather than an ordinary device failure. This often indicates a
corrupt filesystem.

This page last modified on 2022-02-08 12:34:22 UTC

SQLite

Small. Fast. Reliable.
Choose any three.

SQLite C Interface

int sqlite3_errcode(sqlite3 *db);
int sqlite3_extended_errcode(sqlite3 *db);
const char *sqlite3_errmsg(sqlite3*);
const void *sqlite3_errmsg16(sqlite3*);
const char *sqlite3_errstr(int);
int sqlite3_error_offset(sqlite3 *db);

If the most recent sqlite3_* API call associated with
database connection D failed, then the sqlite3_errcode(D) interface
returns the numeric result code or extended result code for that
API call.
The sqlite3_extended_errcode()
interface is the same except that it always returns the
extended result code even when extended result codes are
disabled.

The values returned by sqlite3_errcode() and/or
sqlite3_extended_errcode() might change with each API call.
Except, there are some interfaces that are guaranteed to never
change the value of the error code. The error-code preserving
interfaces include the following:

  • sqlite3_errcode()
  • sqlite3_extended_errcode()
  • sqlite3_errmsg()
  • sqlite3_errmsg16()
  • sqlite3_error_offset()

The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
text that describes the error, as either UTF-8 or UTF-16 respectively.
Memory to hold the error message string is managed internally.
The application does not need to worry about freeing the result.
However, the error string might be overwritten or deallocated by
subsequent calls to other SQLite interface functions.

The sqlite3_errstr() interface returns the English-language text
that describes the result code, as UTF-8.
Memory to hold the error message string is managed internally
and must not be freed by the application.

If the most recent error references a specific token in the input
SQL, the sqlite3_error_offset() interface returns the byte offset
of the start of that token. The byte offset returned by
sqlite3_error_offset() assumes that the input SQL is UTF8.
If the most recent error does not reference a specific token in the input
SQL, then the sqlite3_error_offset() function returns -1.

When the serialized threading mode is in use, it might be the
case that a second error occurs on a separate thread in between
the time of the first error and the call to these interfaces.
When that happens, the second error will be reported since these
interfaces always report the most recent result. To avoid
this, each thread can obtain exclusive use of the database connection D
by invoking sqlite3_mutex_enter(sqlite3_db_mutex(D)) before beginning
to use D and invoking sqlite3_mutex_leave(sqlite3_db_mutex(D)) after
all calls to the interfaces listed here are completed.

If an interface fails with SQLITE_MISUSE, that means the interface
was invoked incorrectly by the application. In that case, the
error code and message may or may not be set.

See also lists of
Objects,
Constants, and
Functions.

Python uses exceptions to indicate an error has
happened. The SQLite library uses integer error codes. APSW maps between the two
systems as needed. Exceptions raised in Python code called by SQLite
will have that exception present when control returns to Python, and
SQLite will understand that an error occurred.

Unraisable¶

There are a few places where it is not possible for a Python exception
to be reported to SQLite as an error, typically because SQLite does
not allow an error to be signalled in that context. Another example
would be in VFS code, because SQLite takes actions to
recover from errors (eg it may try to rollback a transaction on a
write error). Python wants to return to callers, not continue
execution while the exception is pending. (Also only one exception
can be active at a time.)

Unraisable exceptions in VFS code are handled by calling
VFS.excepthook() or VFSFile.excepthook() (more info). In other code sys.unraisablehook is
called, and if that is not present then sys.excepthook is
called.

sqlite3_log is also called
so that you will have the context of when the exception happened
relative to the errors SQLite is logging.

Exception Classes¶

exception Error

This is the base for APSW exceptions.

Error.result

For exceptions corresponding to SQLite error codes codes this attribute
is the numeric error code.

Error.extendedresult

APSW runs with extended result codes turned on.
This attribute includes the detailed code.

Error.error_offset

The location of the error in the SQL when encoded in UTF-8.
The value is from sqlite3_error_offset.

As an example, if SQLite issued a read request and the system returned
less data than expected then result would have the value
SQLITE_IOERR while extendedresult would have
the value SQLITE_IOERR_SHORT_READ.

APSW specific exceptions¶

The following exceptions happen when APSW detects various problems.

exception ThreadingViolationError

You have used an object concurrently in two threads. For example you
may try to use the same cursor in two different threads at the same
time, or tried to close the same connection in two threads at the
same time.

You can also get this exception by using a cursor as an argument to
itself (eg as the input data for Cursor.executemany()).
Cursors can only be used for one thing at a time.

exception ForkingViolationError

See apsw.fork_checker().

exception IncompleteExecutionError

You have tried to start a new SQL execute call before executing all
the previous ones. See the execution model
for more details.

exception ConnectionNotClosedError

This exception is no longer generated. It was required in earlier
releases due to constraints in threading usage with SQLite.

exception ConnectionClosedError

You have called Connection.close() and then continued to use
the Connection or associated cursors.

exception CursorClosedError

You have called Cursor.close() and then tried to use the cursor.

exception BindingsError

There are several causes for this exception. When using tuples, an incorrect number of bindings where supplied:

cursor.execute("select ?,?,?", (1,2))     # too few bindings
cursor.execute("select ?,?,?", (1,2,3,4)) # too many bindings

You are using named bindings, but not all bindings are named. You should either use entirely the
named style or entirely numeric (unnamed) style:

cursor.execute("select * from foo where x=:name and y=?")

Note

It is not considered an error to have missing keys in a dictionary. For example this is perfectly valid:

cursor.execute("insert into foo values($a,:b,$c)", {'a': 1})

b and c are not in the dict. For missing keys, None/NULL
will be used. This is so you don’t have to add lots of spurious
values to the supplied dict. If your schema requires every column
have a value, then SQLite will generate an error due to some
values being None/NULL so that case will be caught.

exception ExecutionCompleteError

A statement is complete but you try to run it more anyway!

exception ExecTraceAbort

The execution tracer returned False so
execution was aborted.

exception ExtensionLoadingError

An error happened loading an extension.

exception VFSNotImplementedError

A call cannot be made to an inherited Virtual File System (VFS) method as the VFS
does not implement the method.

exception VFSFileClosedError

The VFS file is closed so the operation cannot be performed.

SQLite Exceptions¶

The following lists which Exception classes correspond to which SQLite
error codes.

General Errors¶

exception SQLError

SQLITE_ERROR. This error is documented as a bad SQL query
or missing database, but is also returned for a lot of other
situations. It is the default error code unless there is a more
specific one.

exception MismatchError

SQLITE_MISMATCH. Data type mismatch. For example a rowid
or integer primary key must be an integer.

exception NotFoundError

SQLITE_NOTFOUND. Returned when various internal items were
not found such as requests for non-existent system calls or file
controls.

Internal Errors¶

exception InternalError

SQLITE_INTERNAL. (No longer used) Internal logic error in SQLite.

exception ProtocolError

SQLITE_PROTOCOL. (No longer used) Database lock protocol error.

exception MisuseError

SQLITE_MISUSE. SQLite library used incorrectly — typically similar to ValueError in Python. Examples include not
having enough flags when opening a connection (eg not including a READ or WRITE flag), or out of spec such as registering
a function with more than 127 parameters.

exception RangeError

SQLITE_RANGE. (Cannot be generated using APSW). 2nd parameter to sqlite3_bind out of range

Permissions Etc¶

exception PermissionsError

SQLITE_PERM. Access permission denied by the operating system, or parts of the database are readonly such as a cursor.

exception ReadOnlyError

SQLITE_READONLY. Attempt to write to a readonly database.

exception CantOpenError

SQLITE_CANTOPEN. Unable to open the database file.

exception AuthError

SQLITE_AUTH. Authorization denied.

Abort/Busy Etc¶

exception AbortError

SQLITE_ABORT. Callback routine requested an abort.

exception BusyError

SQLITE_BUSY. The database file is locked. Use
Connection.setbusytimeout() to change how long SQLite waits
for the database to be unlocked or Connection.setbusyhandler()
to use your own handler.

exception LockedError

SQLITE_LOCKED. A table in the database is locked.

exception InterruptError

SQLITE_INTERRUPT. Operation terminated by
sqlite3_interrupt —
use Connection.interrupt().

exception SchemaChangeError

SQLITE_SCHEMA. The database schema changed. A
prepared statement becomes invalid
if the database schema was changed. Behind the scenes SQLite
reprepares the statement. Another or the same Connection
may change the schema again before the statement runs. SQLite will
attempt up to 5 times before giving up and returning this error.

exception ConstraintError

SQLITE_CONSTRAINT. Abort due to constraint violation. This
would happen if the schema required a column to be within a specific
range. If you have multiple constraints, you can’t tell
which one was the cause.

Memory/Disk¶

exception NoMemError

SQLITE_NOMEM. A memory allocation failed.

exception IOError

SQLITE_IOERR. Some kind of disk I/O error occurred. The
extended error code will give more detail.

exception CorruptError

SQLITE_CORRUPT. The database disk image appears to be a
SQLite database but the values inside are inconsistent.

exception FullError

SQLITE_FULL. The disk appears to be full.

exception TooBigError

SQLITE_TOOBIG. String or BLOB exceeds size limit. You can
change the limits using Connection.limit().

exception NoLFSError

SQLITE_NOLFS. SQLite has attempted to use a feature not
supported by the operating system such as large file support.

exception EmptyError

SQLITE_EMPTY. Database is completely empty.

exception FormatError

SQLITE_FORMAT. (No longer used) Auxiliary database format error.

exception NotADBError

SQLITE_NOTADB. File opened that is not a database file.
SQLite has a header on database files to verify they are indeed
SQLite databases.

Augmented stack traces¶

When an exception occurs, Python does not include frames from
non-Python code (ie the C code called from Python). This can make it
more difficult to work out what was going on when an exception
occurred for example when there are callbacks to collations, functions
or virtual tables, triggers firing etc.

This is an example showing the difference between the tracebacks you
would have got with earlier versions of apsw and the augmented
traceback:

import apsw

def myfunc(x):
  1/0

con=apsw.Connection(":memory:")
con.createscalarfunction("foo", myfunc)
con.createscalarfunction("fam", myfunc)
cursor=con.cursor()
cursor.execute("create table bar(x,y,z);insert into bar values(1,2,3)")
cursor.execute("select foo(1) from bar")

Original Traceback

Traceback (most recent call last):
  File "t.py", line 11, in <module>
    cursor.execute("select foo(1) from bar")
  File "t.py", line 4, in myfunc
    1/0
ZeroDivisionError: integer division or modulo by zero

Augmented Traceback

Traceback (most recent call last):
  File "t.py", line 11, in <module>
    cursor.execute("select foo(1) from bar")
  File "apsw.c", line 3412, in resetcursor
  File "apsw.c", line 1597, in user-defined-scalar-foo
  File "t.py", line 4, in myfunc
    1/0
ZeroDivisionError: integer division or modulo by zero

In the original traceback you can’t even see that code in apsw was
involved. The augmented traceback shows that there were indeed two
function calls within apsw and gives you line numbers should you need
to examine the code. Also note how you are told that the call was in
user-defined-scalar-foo (ie you can tell which function was called.)

But wait, there is more!!! In order to further aid troubleshooting,
the augmented stack traces make additional information available. Each
frame in the traceback has local variables defined with more
information. You can use apsw.ext.print_augmented_traceback() to
print an exception with the local variables.

Here is a far more complex example from some virtual tables code I was writing. The BestIndex method in my code
had returned an incorrect value. The augmented traceback includes
local variables. I can see what was passed in to my method, what I
returned and which item was erroneous. The original traceback is
almost completely useless!

Original traceback:

Traceback (most recent call last):
  File "tests.py", line 1387, in testVtables
    cursor.execute(allconstraints)
TypeError: Bad constraint (#2) - it should be one of None, an integer or a tuple of an integer and a boolean

Augmented traceback with local variables:

Traceback (most recent call last):
  File "tests.py", line 1387, in testVtables
    cursor.execute(allconstraints)
                VTable =  __main__.VTable
                   cur =  <apsw.Cursor object at 0x988f30>
                     i =  10
                  self =  testVtables (__main__.APSW)
        allconstraints =  select rowid,* from foo where rowid>-1000 ....

  File "apsw.c", line 4050, in Cursor_execute.sqlite3_prepare
            Connection =  <apsw.Connection object at 0x978800>
             statement =  select rowid,* from foo where rowid>-1000 ....

  File "apsw.c", line 2681, in VirtualTable.xBestIndex
                  self =  <__main__.VTable instance at 0x98d8c0>
                  args =  (((-1, 4), (0, 32), (1, 8), (2, 4), (3, 64)), ((2, False),))
                result =  ([4, (3,), [2, False], [1], [0]], 997, u'xea', False)

  File "apsw.c", line 2559, in VirtualTable.xBestIndex.result_constraint
               indices =  [4, (3,), [2, False], [1], [0]]
                  self =  <__main__.VTable instance at 0x98d8c0>
                result =  ([4, (3,), [2, False], [1], [0]], 997, u'xea', False)
            constraint =  (3,)

TypeError: Bad constraint (#2) - it should be one of None, an integer or a tuple of an integer and a boolean
int sqlite3_errcode(sqlite3 *db);
int sqlite3_extended_errcode(sqlite3 *db);
const char *sqlite3_errmsg(sqlite3*);
const void *sqlite3_errmsg16(sqlite3*);
const char *sqlite3_errstr(int);

If the most recent sqlite3_* API call associated with database connection D failed, then the sqlite3_errcode(D) interface returns the numeric result code or extended result code for that API call. If the most recent API call was successful, then the return value from sqlite3_errcode() is undefined. The sqlite3_extended_errcode() interface is the same except that it always returns the extended result code even when extended result codes are disabled.

The sqlite3_errmsg() and sqlite3_errmsg16() return English-language text that describes the error, as either UTF-8 or UTF-16 respectively. Memory to hold the error message string is managed internally. The application does not need to worry about freeing the result. However, the error string might be overwritten or deallocated by subsequent calls to other SQLite interface functions.

The sqlite3_errstr() interface returns the English-language text that describes the result code, as UTF-8. Memory to hold the error message string is managed internally and must not be freed by the application.

When the serialized threading mode is in use, it might be the case that a second error occurs on a separate thread in between the time of the first error and the call to these interfaces. When that happens, the second error will be reported since these interfaces always report the most recent result. To avoid this, each thread can obtain exclusive use of the database connection D by invoking sqlite3_mutex_enter(sqlite3_db_mutex(D)) before beginning to use D and invoking sqlite3_mutex_leave(sqlite3_db_mutex(D)) after all calls to the interfaces listed here are completed.

If an interface fails with SQLITE_MISUSE, that means the interface was invoked incorrectly by the application. In that case, the error code and message may or may not be set.

See also lists of Objects, Constants, and Functions.

Содержание:

  • Исключение sqlite3.Warning,
  • Исключение sqlite3.Error,
  • Исключение sqlite3.DatabaseError,
  • Исключение sqlite3.IntegrityError,
  • Исключение sqlite3.ProgrammingError,
  • Исключение sqlite3.OperationalError,
  • Исключение sqlite3.NotSupportedError,

sqlite3.Warning:

Исключение sqlite3.Warning в настоящее время не вызывается модулем sqlite3, но может быть вызвано приложениями, использующими sqlite3, например, если определяемая пользователем функция обрезает данные при вставке.

Исключение sqlite3.Warning является подклассом Exception.

sqlite3.Error:

Исключение sqlite3.Error представляет собой базовый класс других исключений в этом модуле. Используйте это, чтобы поймать все ошибки с помощью одного единственного оператора.

Если исключение возникло из библиотеки SQLite, то к исключению добавляются следующие два атрибута (добавлено в Python 3.11):

  • sqlite_errorcode — Числовой код ошибки из SQLite API (добавлено в Python 3.11);
  • sqlite_errorname — Символическое имя числового кода ошибки из SQLite API (добавлено в Python 3.11).

sqlite3.DatabaseError:

Исключение sqlite3.DatabaseError возникает из за наличие ошибок, связанных с базой данных.

sqlite3.IntegrityError:

Исключение sqlite3.IntegrityError возникает, когда затрагивается реляционная целостность базы данных, например когда проверка внешнего ключа не удалась.

Это подкласс sqlite3.DatabaseError.

sqlite3.ProgrammingError:

Исключение sqlite3.ProgrammingError возникает из за ошибки программирования, например:

  • таблица не найдена или уже существует,
  • синтаксическая ошибка в операторе SQL,
  • неверное количество указанных параметров и т. д.

Это подкласс sqlite3.DatabaseError.

sqlite3.OperationalError:

Исключение sqlite3.OperationalError возникает при ошибках, связанных с работой базы данных и не обязательно находятся под контролем программиста, например:

  • происходит неожиданное отключение,
  • имя источника данных не найдено,
  • транзакция не может быть обработана и т. д.

Это подкласс sqlite3.DatabaseError.

sqlite3.NotSupportedError:

Исключение sqlite3.NotSupportedError Возникает в случае использования метода или API, который не поддерживается базой данных, например:

  • вызов метода connect.rollback() для соединения, которое не поддерживает транзакции или когда транзакции отключены.

Это подкласс DatabaseError.

Source code: Lib/sqlite3/


SQLite is a C library that provides a lightweight disk-based database that
doesn’t require a separate server process and allows accessing the database
using a nonstandard variant of the SQL query language. Some applications can use
SQLite for internal data storage. It’s also possible to prototype an
application using SQLite and then port the code to a larger database such as
PostgreSQL or Oracle.

The sqlite3 module was written by Gerhard Häring. It provides a SQL interface
compliant with the DB-API 2.0 specification described by PEP 249.

To use the module, you must first create a Connection object that
represents the database. Here the data will be stored in the
example.db file:

import sqlite3
conn = sqlite3.connect('example.db')

You can also supply the special name :memory: to create a database in RAM.

Once you have a Connection, you can create a Cursor object
and call its execute() method to perform SQL commands:

c = conn.cursor()

# Create table
c.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text, qty real, price real)''')

# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

# Save (commit) the changes
conn.commit()

# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()

The data you’ve saved is persistent and is available in subsequent sessions:

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()

Usually your SQL operations will need to use values from Python variables. You
shouldn’t assemble your query using Python’s string operations because doing so
is insecure; it makes your program vulnerable to an SQL injection attack
(see https://xkcd.com/327/ for humorous example of what can go wrong).

Instead, use the DB-API’s parameter substitution. Put ? as a placeholder
wherever you want to use a value, and then provide a tuple of values as the
second argument to the cursor’s execute() method. (Other database
modules may use a different placeholder, such as %s or :1.) For
example:

# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())

# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
             ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
            ]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)

To retrieve data after executing a SELECT statement, you can either treat the
cursor as an iterator, call the cursor’s fetchone() method to
retrieve a single matching row, or call fetchall() to get a list of the
matching rows.

This example uses the iterator form:

>>> for row in c.execute('SELECT * FROM stocks ORDER BY price'):
        print(row)

('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
('2006-04-06', 'SELL', 'IBM', 500, 53.0)
('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)

12.6.1. Module functions and constants¶

sqlite3.version

The version number of this module, as a string. This is not the version of
the SQLite library.

sqlite3.version_info

The version number of this module, as a tuple of integers. This is not the
version of the SQLite library.

sqlite3.sqlite_version

The version number of the run-time SQLite library, as a string.

sqlite3.sqlite_version_info

The version number of the run-time SQLite library, as a tuple of integers.

sqlite3.PARSE_DECLTYPES

This constant is meant to be used with the detect_types parameter of the
connect() function.

Setting it makes the sqlite3 module parse the declared type for each
column it returns. It will parse out the first word of the declared type,
i. e. for “integer primary key”, it will parse out “integer”, or for
“number(10)” it will parse out “number”. Then for that column, it will look
into the converters dictionary and use the converter function registered for
that type there.

sqlite3.PARSE_COLNAMES

This constant is meant to be used with the detect_types parameter of the
connect() function.

Setting this makes the SQLite interface parse the column name for each column it
returns. It will look for a string formed [mytype] in there, and then decide
that ‘mytype’ is the type of the column. It will try to find an entry of
‘mytype’ in the converters dictionary and then use the converter function found
there to return the value. The column name found in Cursor.description
is only the first word of the column name, i. e. if you use something like
'as "x [datetime]"' in your SQL, then we will parse out everything until the
first blank for the column name: the column name would simply be “x”.

sqlite3.connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])

Opens a connection to the SQLite database file database. By default returns a
Connection object, unless a custom factory is given.

database is a path-like object giving the pathname (absolute or
relative to the current working directory) of the database file to be opened.
You can use ":memory:" to open a database connection to a database that
resides in RAM instead of on disk.

When a database is accessed by multiple connections, and one of the processes
modifies the database, the SQLite database is locked until that transaction is
committed. The timeout parameter specifies how long the connection should wait
for the lock to go away until raising an exception. The default for the timeout
parameter is 5.0 (five seconds).

For the isolation_level parameter, please see the
isolation_level property of Connection objects.

SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
you want to use other types you must add support for them yourself. The
detect_types parameter and the using custom converters registered with the
module-level register_converter() function allow you to easily do that.

detect_types defaults to 0 (i. e. off, no type detection), you can set it to
any combination of PARSE_DECLTYPES and PARSE_COLNAMES to turn
type detection on.

By default, check_same_thread is True and only the creating thread may
use the connection. If set False, the returned connection may be shared
across multiple threads. When using multiple threads with the same connection
writing operations should be serialized by the user to avoid data corruption.

By default, the sqlite3 module uses its Connection class for the
connect call. You can, however, subclass the Connection class and make
connect() use your class instead by providing your class for the factory
parameter.

Consult the section SQLite and Python types of this manual for details.

The sqlite3 module internally uses a statement cache to avoid SQL parsing
overhead. If you want to explicitly set the number of statements that are cached
for the connection, you can set the cached_statements parameter. The currently
implemented default is to cache 100 statements.

If uri is true, database is interpreted as a URI. This allows you
to specify options. For example, to open a database in read-only mode
you can use:

db = sqlite3.connect('file:path/to/database?mode=ro', uri=True)

More information about this feature, including a list of recognized options, can
be found in the SQLite URI documentation.

Changed in version 3.4: Added the uri parameter.

Changed in version 3.7: database can now also be a path-like object, not only a string.

sqlite3.register_converter(typename, callable)

Registers a callable to convert a bytestring from the database into a custom
Python type. The callable will be invoked for all database values that are of
the type typename. Confer the parameter detect_types of the connect()
function for how the type detection works. Note that the case of typename and
the name of the type in your query must match!

sqlite3.register_adapter(type, callable)

Registers a callable to convert the custom Python type type into one of
SQLite’s supported types. The callable callable accepts as single parameter
the Python value, and must return a value of the following types: int,
float, str or bytes.

sqlite3.complete_statement(sql)

Returns True if the string sql contains one or more complete SQL
statements terminated by semicolons. It does not verify that the SQL is
syntactically correct, only that there are no unclosed string literals and the
statement is terminated by a semicolon.

This can be used to build a shell for SQLite, as in the following example:

# A minimal SQLite shell for experiments

import sqlite3

con = sqlite3.connect(":memory:")
con.isolation_level = None
cur = con.cursor()

buffer = ""

print("Enter your SQL commands to execute in sqlite3.")
print("Enter a blank line to exit.")

while True:
    line = input()
    if line == "":
        break
    buffer += line
    if sqlite3.complete_statement(buffer):
        try:
            buffer = buffer.strip()
            cur.execute(buffer)

            if buffer.lstrip().upper().startswith("SELECT"):
                print(cur.fetchall())
        except sqlite3.Error as e:
            print("An error occurred:", e.args[0])
        buffer = ""

con.close()
sqlite3.enable_callback_tracebacks(flag)

By default you will not get any tracebacks in user-defined functions,
aggregates, converters, authorizer callbacks etc. If you want to debug them,
you can call this function with flag set to True. Afterwards, you will
get tracebacks from callbacks on sys.stderr. Use False to
disable the feature again.

12.6.2. Connection Objects¶

class sqlite3.Connection

A SQLite database connection has the following attributes and methods:

isolation_level

Get or set the current isolation level. None for autocommit mode or
one of “DEFERRED”, “IMMEDIATE” or “EXCLUSIVE”. See section
Controlling Transactions for a more detailed explanation.

in_transaction

True if a transaction is active (there are uncommitted changes),
False otherwise. Read-only attribute.

New in version 3.2.

cursor(factory=Cursor)

The cursor method accepts a single optional parameter factory. If
supplied, this must be a callable returning an instance of Cursor
or its subclasses.

commit()

This method commits the current transaction. If you don’t call this method,
anything you did since the last call to commit() is not visible from
other database connections. If you wonder why you don’t see the data you’ve
written to the database, please check you didn’t forget to call this method.

rollback()

This method rolls back any changes to the database since the last call to
commit().

close()

This closes the database connection. Note that this does not automatically
call commit(). If you just close your database connection without
calling commit() first, your changes will be lost!

execute(sql[, parameters])

This is a nonstandard shortcut that creates a cursor object by calling
the cursor() method, calls the cursor’s
execute() method with the parameters given, and returns
the cursor.

executemany(sql[, parameters])

This is a nonstandard shortcut that creates a cursor object by
calling the cursor() method, calls the cursor’s
executemany() method with the parameters given, and
returns the cursor.

executescript(sql_script)

This is a nonstandard shortcut that creates a cursor object by
calling the cursor() method, calls the cursor’s
executescript() method with the given sql_script, and
returns the cursor.

create_function(name, num_params, func)

Creates a user-defined function that you can later use from within SQL
statements under the function name name. num_params is the number of
parameters the function accepts (if num_params is -1, the function may
take any number of arguments), and func is a Python callable that is
called as the SQL function.

The function can return any of the types supported by SQLite: bytes, str, int,
float and None.

Example:

import sqlite3
import hashlib

def md5sum(t):
    return hashlib.md5(t).hexdigest()

con = sqlite3.connect(":memory:")
con.create_function("md5", 1, md5sum)
cur = con.cursor()
cur.execute("select md5(?)", (b"foo",))
print(cur.fetchone()[0])
create_aggregate(name, num_params, aggregate_class)

Creates a user-defined aggregate function.

The aggregate class must implement a step method, which accepts the number
of parameters num_params (if num_params is -1, the function may take
any number of arguments), and a finalize method which will return the
final result of the aggregate.

The finalize method can return any of the types supported by SQLite:
bytes, str, int, float and None.

Example:

import sqlite3

class MySum:
    def __init__(self):
        self.count = 0

    def step(self, value):
        self.count += value

    def finalize(self):
        return self.count

con = sqlite3.connect(":memory:")
con.create_aggregate("mysum", 1, MySum)
cur = con.cursor()
cur.execute("create table test(i)")
cur.execute("insert into test(i) values (1)")
cur.execute("insert into test(i) values (2)")
cur.execute("select mysum(i) from test")
print(cur.fetchone()[0])
create_collation(name, callable)

Creates a collation with the specified name and callable. The callable will
be passed two string arguments. It should return -1 if the first is ordered
lower than the second, 0 if they are ordered equal and 1 if the first is ordered
higher than the second. Note that this controls sorting (ORDER BY in SQL) so
your comparisons don’t affect other SQL operations.

Note that the callable will get its parameters as Python bytestrings, which will
normally be encoded in UTF-8.

The following example shows a custom collation that sorts “the wrong way”:

import sqlite3

def collate_reverse(string1, string2):
    if string1 == string2:
        return 0
    elif string1 < string2:
        return 1
    else:
        return -1

con = sqlite3.connect(":memory:")
con.create_collation("reverse", collate_reverse)

cur = con.cursor()
cur.execute("create table test(x)")
cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
cur.execute("select x from test order by x collate reverse")
for row in cur:
    print(row)
con.close()

To remove a collation, call create_collation with None as callable:

con.create_collation("reverse", None)
interrupt()

You can call this method from a different thread to abort any queries that might
be executing on the connection. The query will then abort and the caller will
get an exception.

This routine registers a callback. The callback is invoked for each attempt to
access a column of a table in the database. The callback should return
SQLITE_OK if access is allowed, SQLITE_DENY if the entire SQL
statement should be aborted with an error and SQLITE_IGNORE if the
column should be treated as a NULL value. These constants are available in the
sqlite3 module.

The first argument to the callback signifies what kind of operation is to be
authorized. The second and third argument will be arguments or None
depending on the first argument. The 4th argument is the name of the database
(“main”, “temp”, etc.) if applicable. The 5th argument is the name of the
inner-most trigger or view that is responsible for the access attempt or
None if this access attempt is directly from input SQL code.

Please consult the SQLite documentation about the possible values for the first
argument and the meaning of the second and third argument depending on the first
one. All necessary constants are available in the sqlite3 module.

set_progress_handler(handler, n)

This routine registers a callback. The callback is invoked for every n
instructions of the SQLite virtual machine. This is useful if you want to
get called from SQLite during long-running operations, for example to update
a GUI.

If you want to clear any previously installed progress handler, call the
method with None for handler.

Returning a non-zero value from the handler function will terminate the
currently executing query and cause it to raise an OperationalError
exception.

set_trace_callback(trace_callback)

Registers trace_callback to be called for each SQL statement that is
actually executed by the SQLite backend.

The only argument passed to the callback is the statement (as string) that
is being executed. The return value of the callback is ignored. Note that
the backend does not only run statements passed to the Cursor.execute()
methods. Other sources include the transaction management of the Python
module and the execution of triggers defined in the current database.

Passing None as trace_callback will disable the trace callback.

New in version 3.3.

enable_load_extension(enabled)

This routine allows/disallows the SQLite engine to load SQLite extensions
from shared libraries. SQLite extensions can define new functions,
aggregates or whole new virtual table implementations. One well-known
extension is the fulltext-search extension distributed with SQLite.

Loadable extensions are disabled by default. See [1].

New in version 3.2.

import sqlite3

con = sqlite3.connect(":memory:")

# enable extension loading
con.enable_load_extension(True)

# Load the fulltext search extension
con.execute("select load_extension('./fts3.so')")

# alternatively you can load the extension using an API call:
# con.load_extension("./fts3.so")

# disable extension loading again
con.enable_load_extension(False)

# example from SQLite wiki
con.execute("create virtual table recipe using fts3(name, ingredients)")
con.executescript("""
    insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes');
    insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery');
    insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour');
    insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter');
    """)
for row in con.execute("select rowid, name, ingredients from recipe where name match 'pie'"):
    print(row)
load_extension(path)

This routine loads a SQLite extension from a shared library. You have to
enable extension loading with enable_load_extension() before you can
use this routine.

Loadable extensions are disabled by default. See [1].

New in version 3.2.

row_factory

You can change this attribute to a callable that accepts the cursor and the
original row as a tuple and will return the real result row. This way, you can
implement more advanced ways of returning results, such as returning an object
that can also access columns by name.

Example:

import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print(cur.fetchone()["a"])

If returning a tuple doesn’t suffice and you want name-based access to
columns, you should consider setting row_factory to the
highly-optimized sqlite3.Row type. Row provides both
index-based and case-insensitive name-based access to columns with almost no
memory overhead. It will probably be better than your own custom
dictionary-based approach or even a db_row based solution.

text_factory

Using this attribute you can control what objects are returned for the TEXT
data type. By default, this attribute is set to str and the
sqlite3 module will return Unicode objects for TEXT. If you want to
return bytestrings instead, you can set it to bytes.

You can also set it to any other callable that accepts a single bytestring
parameter and returns the resulting object.

See the following example code for illustration:

import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()

AUSTRIA = "xd6sterreich"

# by default, rows are returned as Unicode
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert row[0] == AUSTRIA

# but we can make sqlite3 always return bytestrings ...
con.text_factory = bytes
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert type(row[0]) is bytes
# the bytestrings will be encoded in UTF-8, unless you stored garbage in the
# database ...
assert row[0] == AUSTRIA.encode("utf-8")

# we can also implement a custom text_factory ...
# here we implement one that appends "foo" to all strings
con.text_factory = lambda x: x.decode("utf-8") + "foo"
cur.execute("select ?", ("bar",))
row = cur.fetchone()
assert row[0] == "barfoo"
total_changes

Returns the total number of database rows that have been modified, inserted, or
deleted since the database connection was opened.

iterdump()

Returns an iterator to dump the database in an SQL text format. Useful when
saving an in-memory database for later restoration. This function provides
the same capabilities as the .dump command in the sqlite3
shell.

Example:

# Convert file existing_db.db to SQL dump file dump.sql
import sqlite3

con = sqlite3.connect('existing_db.db')
with open('dump.sql', 'w') as f:
    for line in con.iterdump():
        f.write('%sn' % line)

12.6.3. Cursor Objects¶

class sqlite3.Cursor

A Cursor instance has the following attributes and methods.

execute(sql[, parameters])

Executes an SQL statement. The SQL statement may be parameterized (i. e.
placeholders instead of SQL literals). The sqlite3 module supports two
kinds of placeholders: question marks (qmark style) and named placeholders
(named style).

Here’s an example of both styles:

import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table people (name_last, age)")

who = "Yeltsin"
age = 72

# This is the qmark style:
cur.execute("insert into people values (?, ?)", (who, age))

# And this is the named style:
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})

print(cur.fetchone())

execute() will only execute a single SQL statement. If you try to execute
more than one statement with it, it will raise a Warning. Use
executescript() if you want to execute multiple SQL statements with one
call.

executemany(sql, seq_of_parameters)

Executes an SQL command against all parameter sequences or mappings found in
the sequence seq_of_parameters. The sqlite3 module also allows
using an iterator yielding parameters instead of a sequence.

import sqlite3

class IterChars:
    def __init__(self):
        self.count = ord('a')

    def __iter__(self):
        return self

    def __next__(self):
        if self.count > ord('z'):
            raise StopIteration
        self.count += 1
        return (chr(self.count - 1),) # this is a 1-tuple

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")

theIter = IterChars()
cur.executemany("insert into characters(c) values (?)", theIter)

cur.execute("select c from characters")
print(cur.fetchall())

Here’s a shorter example using a generator:

import sqlite3
import string

def char_generator():
    for c in string.ascii_lowercase:
        yield (c,)

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")

cur.executemany("insert into characters(c) values (?)", char_generator())

cur.execute("select c from characters")
print(cur.fetchall())
executescript(sql_script)

This is a nonstandard convenience method for executing multiple SQL statements
at once. It issues a COMMIT statement first, then executes the SQL script it
gets as a parameter.

sql_script can be an instance of str.

Example:

import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.executescript("""
    create table person(
        firstname,
        lastname,
        age
    );

    create table book(
        title,
        author,
        published
    );

    insert into book(title, author, published)
    values (
        'Dirk Gently''s Holistic Detective Agency',
        'Douglas Adams',
        1987
    );
    """)
fetchone()

Fetches the next row of a query result set, returning a single sequence,
or None when no more data is available.

fetchmany(size=cursor.arraysize)

Fetches the next set of rows of a query result, returning a list. An empty
list is returned when no more rows are available.

The number of rows to fetch per call is specified by the size parameter.
If it is not given, the cursor’s arraysize determines the number of rows
to be fetched. The method should try to fetch as many rows as indicated by
the size parameter. If this is not possible due to the specified number of
rows not being available, fewer rows may be returned.

Note there are performance considerations involved with the size parameter.
For optimal performance, it is usually best to use the arraysize attribute.
If the size parameter is used, then it is best for it to retain the same
value from one fetchmany() call to the next.

fetchall()

Fetches all (remaining) rows of a query result, returning a list. Note that
the cursor’s arraysize attribute can affect the performance of this operation.
An empty list is returned when no rows are available.

close()

Close the cursor now (rather than whenever __del__ is called).

The cursor will be unusable from this point forward; a ProgrammingError
exception will be raised if any operation is attempted with the cursor.

rowcount

Although the Cursor class of the sqlite3 module implements this
attribute, the database engine’s own support for the determination of “rows
affected”/”rows selected” is quirky.

For executemany() statements, the number of modifications are summed up
into rowcount.

As required by the Python DB API Spec, the rowcount attribute “is -1 in
case no executeXX() has been performed on the cursor or the rowcount of the
last operation is not determinable by the interface”. This includes SELECT
statements because we cannot determine the number of rows a query produced
until all rows were fetched.

With SQLite versions before 3.6.5, rowcount is set to 0 if
you make a DELETE FROM table without any condition.

lastrowid

This read-only attribute provides the rowid of the last modified row. It is
only set if you issued an INSERT or a REPLACE statement using the
execute() method. For operations other than INSERT or
REPLACE or when executemany() is called, lastrowid is
set to None.

If the INSERT or REPLACE statement failed to insert the previous
successful rowid is returned.

Changed in version 3.6: Added support for the REPLACE statement.

arraysize

Read/write attribute that controls the number of rows returned by fetchmany().
The default value is 1 which means a single row would be fetched per call.

description

This read-only attribute provides the column names of the last query. To
remain compatible with the Python DB API, it returns a 7-tuple for each
column where the last six items of each tuple are None.

It is set for SELECT statements without any matching rows as well.

connection

This read-only attribute provides the SQLite database Connection
used by the Cursor object. A Cursor object created by
calling con.cursor() will have a
connection attribute that refers to con:

>>> con = sqlite3.connect(":memory:")
>>> cur = con.cursor()
>>> cur.connection == con
True

12.6.4. Row Objects¶

class sqlite3.Row

A Row instance serves as a highly optimized
row_factory for Connection objects.
It tries to mimic a tuple in most of its features.

It supports mapping access by column name and index, iteration,
representation, equality testing and len().

If two Row objects have exactly the same columns and their
members are equal, they compare equal.

keys()

This method returns a list of column names. Immediately after a query,
it is the first member of each tuple in Cursor.description.

Changed in version 3.5: Added support of slicing.

Let’s assume we initialize a table as in the example given above:

conn = sqlite3.connect(":memory:")
c = conn.cursor()
c.execute('''create table stocks
(date text, trans text, symbol text,
 qty real, price real)''')
c.execute("""insert into stocks
          values ('2006-01-05','BUY','RHAT',100,35.14)""")
conn.commit()
c.close()

Now we plug Row in:

>>> conn.row_factory = sqlite3.Row
>>> c = conn.cursor()
>>> c.execute('select * from stocks')
<sqlite3.Cursor object at 0x7f4e7dd8fa80>
>>> r = c.fetchone()
>>> type(r)
<class 'sqlite3.Row'>
>>> tuple(r)
('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
>>> len(r)
5
>>> r[2]
'RHAT'
>>> r.keys()
['date', 'trans', 'symbol', 'qty', 'price']
>>> r['qty']
100.0
>>> for member in r:
...     print(member)
...
2006-01-05
BUY
RHAT
100.0
35.14

12.6.5. Exceptions¶

exception sqlite3.Warning

A subclass of Exception.

exception sqlite3.Error

The base class of the other exceptions in this module. It is a subclass
of Exception.

exception sqlite3.DatabaseError

Exception raised for errors that are related to the database.

exception sqlite3.IntegrityError

Exception raised when the relational integrity of the database is affected,
e.g. a foreign key check fails. It is a subclass of DatabaseError.

exception sqlite3.ProgrammingError

Exception raised for programming errors, e.g. table not found or already
exists, syntax error in the SQL statement, wrong number of parameters
specified, etc. It is a subclass of DatabaseError.

12.6.6. SQLite and Python types¶

12.6.6.1. Introduction¶

SQLite natively supports the following types: NULL, INTEGER,
REAL, TEXT, BLOB.

The following Python types can thus be sent to SQLite without any problem:

Python type SQLite type
None NULL
int INTEGER
float REAL
str TEXT
bytes BLOB

This is how SQLite types are converted to Python types by default:

SQLite type Python type
NULL None
INTEGER int
REAL float
TEXT depends on text_factory,
str by default
BLOB bytes

The type system of the sqlite3 module is extensible in two ways: you can
store additional Python types in a SQLite database via object adaptation, and
you can let the sqlite3 module convert SQLite types to different Python
types via converters.

12.6.6.2. Using adapters to store additional Python types in SQLite databases¶

As described before, SQLite supports only a limited set of types natively. To
use other Python types with SQLite, you must adapt them to one of the
sqlite3 module’s supported types for SQLite: one of NoneType, int, float,
str, bytes.

There are two ways to enable the sqlite3 module to adapt a custom Python
type to one of the supported ones.

12.6.6.2.1. Letting your object adapt itself¶

This is a good approach if you write the class yourself. Let’s suppose you have
a class like this:

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

Now you want to store the point in a single SQLite column. First you’ll have to
choose one of the supported types first to be used for representing the point.
Let’s just use str and separate the coordinates using a semicolon. Then you need
to give your class a method __conform__(self, protocol) which must return
the converted value. The parameter protocol will be PrepareProtocol.

import sqlite3

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __conform__(self, protocol):
        if protocol is sqlite3.PrepareProtocol:
            return "%f;%f" % (self.x, self.y)

con = sqlite3.connect(":memory:")
cur = con.cursor()

p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print(cur.fetchone()[0])

12.6.6.2.2. Registering an adapter callable¶

The other possibility is to create a function that converts the type to the
string representation and register the function with register_adapter().

import sqlite3

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

def adapt_point(point):
    return "%f;%f" % (point.x, point.y)

sqlite3.register_adapter(Point, adapt_point)

con = sqlite3.connect(":memory:")
cur = con.cursor()

p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print(cur.fetchone()[0])

The sqlite3 module has two default adapters for Python’s built-in
datetime.date and datetime.datetime types. Now let’s suppose
we want to store datetime.datetime objects not in ISO representation,
but as a Unix timestamp.

import sqlite3
import datetime
import time

def adapt_datetime(ts):
    return time.mktime(ts.timetuple())

sqlite3.register_adapter(datetime.datetime, adapt_datetime)

con = sqlite3.connect(":memory:")
cur = con.cursor()

now = datetime.datetime.now()
cur.execute("select ?", (now,))
print(cur.fetchone()[0])

12.6.6.3. Converting SQLite values to custom Python types¶

Writing an adapter lets you send custom Python types to SQLite. But to make it
really useful we need to make the Python to SQLite to Python roundtrip work.

Enter converters.

Let’s go back to the Point class. We stored the x and y coordinates
separated via semicolons as strings in SQLite.

First, we’ll define a converter function that accepts the string as a parameter
and constructs a Point object from it.

Note

Converter functions always get called with a bytes object, no
matter under which data type you sent the value to SQLite.

def convert_point(s):
    x, y = map(float, s.split(b";"))
    return Point(x, y)

Now you need to make the sqlite3 module know that what you select from
the database is actually a point. There are two ways of doing this:

  • Implicitly via the declared type
  • Explicitly via the column name

Both ways are described in section Module functions and constants, in the entries
for the constants PARSE_DECLTYPES and PARSE_COLNAMES.

The following example illustrates both approaches.

import sqlite3

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return "(%f;%f)" % (self.x, self.y)

def adapt_point(point):
    return ("%f;%f" % (point.x, point.y)).encode('ascii')

def convert_point(s):
    x, y = list(map(float, s.split(b";")))
    return Point(x, y)

# Register the adapter
sqlite3.register_adapter(Point, adapt_point)

# Register the converter
sqlite3.register_converter("point", convert_point)

p = Point(4.0, -3.2)

#########################
# 1) Using declared types
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute("create table test(p point)")

cur.execute("insert into test(p) values (?)", (p,))
cur.execute("select p from test")
print("with declared types:", cur.fetchone()[0])
cur.close()
con.close()

#######################
# 1) Using column names
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(p)")

cur.execute("insert into test(p) values (?)", (p,))
cur.execute('select p as "p [point]" from test')
print("with column names:", cur.fetchone()[0])
cur.close()
con.close()

12.6.6.4. Default adapters and converters¶

There are default adapters for the date and datetime types in the datetime
module. They will be sent as ISO dates/ISO timestamps to SQLite.

The default converters are registered under the name “date” for
datetime.date and under the name “timestamp” for
datetime.datetime.

This way, you can use date/timestamps from Python without any additional
fiddling in most cases. The format of the adapters is also compatible with the
experimental SQLite date/time functions.

The following example demonstrates this.

import sqlite3
import datetime

con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(d date, ts timestamp)")

today = datetime.date.today()
now = datetime.datetime.now()

cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
cur.execute("select d, ts from test")
row = cur.fetchone()
print(today, "=>", row[0], type(row[0]))
print(now, "=>", row[1], type(row[1]))

cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"')
row = cur.fetchone()
print("current_date", row[0], type(row[0]))
print("current_timestamp", row[1], type(row[1]))

If a timestamp stored in SQLite has a fractional part longer than 6
numbers, its value will be truncated to microsecond precision by the
timestamp converter.

12.6.7. Controlling Transactions¶

By default, the sqlite3 module opens transactions implicitly before a
Data Modification Language (DML) statement (i.e.
INSERT/UPDATE/DELETE/REPLACE).

You can control which kind of BEGIN statements sqlite3 implicitly executes
(or none at all) via the isolation_level parameter to the connect()
call, or via the isolation_level property of connections.

If you want autocommit mode, then set isolation_level to None.

Otherwise leave it at its default, which will result in a plain “BEGIN”
statement, or set it to one of SQLite’s supported isolation levels: “DEFERRED”,
“IMMEDIATE” or “EXCLUSIVE”.

The current transaction state is exposed through the
Connection.in_transaction attribute of the connection object.

Changed in version 3.6: sqlite3 used to implicitly commit an open transaction before DDL
statements. This is no longer the case.

12.6.8. Using sqlite3 efficiently¶

12.6.8.1. Using shortcut methods¶

Using the nonstandard execute(), executemany() and
executescript() methods of the Connection object, your code can
be written more concisely because you don’t have to create the (often
superfluous) Cursor objects explicitly. Instead, the Cursor
objects are created implicitly and these shortcut methods return the cursor
objects. This way, you can execute a SELECT statement and iterate over it
directly using only a single call on the Connection object.

import sqlite3

persons = [
    ("Hugo", "Boss"),
    ("Calvin", "Klein")
    ]

con = sqlite3.connect(":memory:")

# Create the table
con.execute("create table person(firstname, lastname)")

# Fill the table
con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)

# Print the table contents
for row in con.execute("select firstname, lastname from person"):
    print(row)

print("I just deleted", con.execute("delete from person").rowcount, "rows")

12.6.8.2. Accessing columns by name instead of by index¶

One useful feature of the sqlite3 module is the built-in
sqlite3.Row class designed to be used as a row factory.

Rows wrapped with this class can be accessed both by index (like tuples) and
case-insensitively by name:

import sqlite3

con = sqlite3.connect(":memory:")
con.row_factory = sqlite3.Row

cur = con.cursor()
cur.execute("select 'John' as name, 42 as age")
for row in cur:
    assert row[0] == row["name"]
    assert row["name"] == row["nAmE"]
    assert row[1] == row["age"]
    assert row[1] == row["AgE"]

12.6.8.3. Using the connection as a context manager¶

Connection objects can be used as context managers
that automatically commit or rollback transactions. In the event of an
exception, the transaction is rolled back; otherwise, the transaction is
committed:

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("create table person (id integer primary key, firstname varchar unique)")

# Successful, con.commit() is called automatically afterwards
with con:
    con.execute("insert into person(firstname) values (?)", ("Joe",))

# con.rollback() is called after the with block finishes with an exception, the
# exception is still raised and must be caught
try:
    with con:
        con.execute("insert into person(firstname) values (?)", ("Joe",))
except sqlite3.IntegrityError:
    print("couldn't add Joe twice")

12.6.9. Common issues¶

12.6.9.1. Multithreading¶

Older SQLite versions had issues with sharing connections between threads.
That’s why the Python module disallows sharing connections and cursors between
threads. If you still try to do so, you will get an exception at runtime.

The only exception is calling the interrupt() method, which
only makes sense to call from a different thread.

Footnotes

[1] (1, 2) The sqlite3 module is not built with loadable extension support by
default, because some platforms (notably Mac OS X) have SQLite
libraries which are compiled without this feature. To get loadable
extension support, you must pass –enable-loadable-sqlite-extensions to
configure.

Понравилась статья? Поделить с друзьями:
  • Sqlite как изменить тип данных столбца
  • Sql state im003 native 160 ошибка 182 sqlsrv32 dll windows 10
  • Sqlite как изменить название столбца
  • Sql state hyt00 sql error code 0
  • Sqlite trigger error