On this page
sqlite3
Prev: socketserver | Up: stdlib_module | Next: sre_compile
Rel: pickle, copyreg, shelve, marshal, dbm, SQLite3 Guide, SQL
Ref: docs.python.org — sqlite3
Tags: #public #python3 #stdlib
Import
import sqlite3
Overview
Embedded, zero-server relational SQL database engine built directly into Python's standard library (DB-API 2.0). Reach for sqlite3 whenever an application needs durable, ACID-transactional structured storage, indexes, or SQL queries without operating a separate database server.
Quick Start
import sqlite3
with sqlite3.connect(":memory:") as conn:
conn.row_factory = sqlite3.Row
conn.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
conn.execute("INSERT INTO items (name) VALUES (?)", ("notebook",))
row = conn.execute("SELECT id, name FROM items WHERE name = ?", ("notebook",)).fetchone()
assert dict(row) == {"id": 1, "name": "notebook"}
Implementation Walkthrough
1. Safe Parameterized Queries, Transactions & WAL Mode
Always use ? or :name placeholders (never f-strings) to prevent SQL injection, and enable foreign keys + WAL mode on file-backed databases:
import sqlite3
from contextlib import closing
def open_db(path: str) -> sqlite3.Connection:
conn = sqlite3.connect(path, timeout=10.0)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA journal_mode = WAL")
return conn
with closing(open_db(":memory:")) as conn:
with conn: # commits on success, rolls back on exception
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE)")
conn.executemany(
"INSERT INTO users (email) VALUES (?)",
[("ada@example.org",), ("grace@example.org",)],
)
Gotchas & Boundaries
with conn:commits/rolls back, it does NOT close the connection: Wrap withcontextlib.closing(conn)or callconn.close()infinallyto avoid leaking file descriptors.- Foreign key enforcement is OFF by default in SQLite: Run
PRAGMA foreign_keys = ONon every new connection. - Never interpolate values into SQL strings: Always pass parameters as a tuple
(val,)(note the trailing comma for single-element tuples) or dict{...}. - Connections aren't shared across threads by default: Open one connection per thread or serialize writes through a single writer.
Common Functions
- sqlite3.adapt() —
adapt(...)— Adapt given object to given protocol. - sqlite3.complete_statement() —
complete_statement(statement)— Checks if a string contains a complete SQL statement. - sqlite3.connect() —
connect(...)— Open a connection to the SQLite database file 'database'. - sqlite3.DateFromTicks() —
DateFromTicks(ticks)—sqlite3.DateFromTicks()function. - sqlite3.enable_callback_tracebacks() —
enable_callback_tracebacks(enable, /)— Enable or disable callback functions throwing errors to stderr. - sqlite3.register_adapter() —
register_adapter(type, adapter, /)— Register a function to adapt Python objects to SQLite values. - sqlite3.register_converter() —
register_converter(typename, converter, /)— Register a function to convert SQLite values to Python objects. - sqlite3.TimeFromTicks() —
TimeFromTicks(ticks)—sqlite3.TimeFromTicks()function. - sqlite3.TimestampFromTicks() —
TimestampFromTicks(ticks)—sqlite3.TimestampFromTicks()function.
Classes & Objects
- sqlite3.Binary — Create a new memoryview object which references the given object. (Methods:
.cast(),.count(),.hex(),.index(),.release(),.tobytes()) - sqlite3.Blob —
sqlite3.Blobclass. (Methods:.close(),.read(),.seek(),.tell(),.write()) - sqlite3.Connection — SQLite database connection object. (Methods:
.backup(),.blobopen(),.close(),.commit(),.create_aggregate(),.create_collation()) - sqlite3.Cursor — SQLite database cursor class. (Methods:
.close(),.execute(),.executemany(),.executescript(),.fetchall(),.fetchmany()) - sqlite3.DatabaseError —
sqlite3.DatabaseErrorclass. (Methods:.add_note(),.with_traceback()) - sqlite3.DataError —
sqlite3.DataErrorclass. (Methods:.add_note(),.with_traceback()) - sqlite3.Date — date(year, month, day) --> date object (Methods:
.ctime(),.fromisocalendar(),.fromisoformat(),.fromordinal(),.fromtimestamp(),.isocalendar()) - sqlite3.Error —
sqlite3.Errorclass. (Methods:.add_note(),.with_traceback()) - sqlite3.IntegrityError —
sqlite3.IntegrityErrorclass. (Methods:.add_note(),.with_traceback()) - sqlite3.InterfaceError —
sqlite3.InterfaceErrorclass. (Methods:.add_note(),.with_traceback()) - sqlite3.InternalError —
sqlite3.InternalErrorclass. (Methods:.add_note(),.with_traceback()) - sqlite3.NotSupportedError —
sqlite3.NotSupportedErrorclass. (Methods:.add_note(),.with_traceback()) - sqlite3.OperationalError —
sqlite3.OperationalErrorclass. (Methods:.add_note(),.with_traceback()) - sqlite3.PrepareProtocol — PEP 246 style object adaption protocol type.
- sqlite3.ProgrammingError —
sqlite3.ProgrammingErrorclass. (Methods:.add_note(),.with_traceback()) - sqlite3.Row —
sqlite3.Rowclass. (Methods:.keys()) - sqlite3.Time — All arguments are optional. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints. (Methods:
.dst(),.fromisoformat(),.isoformat(),.replace(),.strftime(),.strptime()) - sqlite3.Timestamp — The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints. (Methods:
.astimezone(),.combine(),.ctime(),.date(),.dst(),.fromisocalendar()) - sqlite3.Warning —
sqlite3.Warningclass. (Methods:.add_note(),.with_traceback())
Constants & Attributes
sqlite3.LEGACY_TRANSACTION_CONTROL(int) =-1sqlite3.PARSE_COLNAMES(int) =2sqlite3.PARSE_DECLTYPES(int) =1sqlite3.SQLITE_ABORT(int) =4sqlite3.SQLITE_ABORT_ROLLBACK(int) =516sqlite3.SQLITE_ALTER_TABLE(int) =26sqlite3.SQLITE_ANALYZE(int) =28sqlite3.SQLITE_ATTACH(int) =24sqlite3.SQLITE_AUTH(int) =23sqlite3.SQLITE_AUTH_USER(int) =279sqlite3.SQLITE_BUSY(int) =5sqlite3.SQLITE_BUSY_RECOVERY(int) =261sqlite3.SQLITE_BUSY_SNAPSHOT(int) =517sqlite3.SQLITE_BUSY_TIMEOUT(int) =773sqlite3.SQLITE_CANTOPEN(int) =14
Linked from
- tuts/databases
- tuts/databases/sqlite3
- tuts/databases/sqlite3/architecture_and_type_affinity
- tuts/databases/sqlite3/python_sqlite3_patterns
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/copyreg
- tuts/python3/stdlib_module/dbm
- tuts/python3/stdlib_module/marshal
- tuts/python3/stdlib_module/pickle
- tuts/python3/stdlib_module/shelve
- tuts/python3/stdlib_module/socketserver
- tuts/python3/stdlib_module/sqlite3/adapt
- tuts/python3/stdlib_module/sqlite3/Binary
- tuts/python3/stdlib_module/sqlite3/Blob
- tuts/python3/stdlib_module/sqlite3/complete_statement
- tuts/python3/stdlib_module/sqlite3/connect
- tuts/python3/stdlib_module/sqlite3/Connection
- tuts/python3/stdlib_module/sqlite3/Cursor
- tuts/python3/stdlib_module/sqlite3/DatabaseError
- tuts/python3/stdlib_module/sqlite3/DataError
- tuts/python3/stdlib_module/sqlite3/Date
- tuts/python3/stdlib_module/sqlite3/DateFromTicks
- tuts/python3/stdlib_module/sqlite3/enable_callback_tracebacks
- tuts/python3/stdlib_module/sqlite3/Error
- tuts/python3/stdlib_module/sqlite3/IntegrityError
- tuts/python3/stdlib_module/sqlite3/InterfaceError
- tuts/python3/stdlib_module/sqlite3/InternalError
- tuts/python3/stdlib_module/sqlite3/NotSupportedError
- tuts/python3/stdlib_module/sqlite3/OperationalError
- tuts/python3/stdlib_module/sqlite3/PrepareProtocol
- tuts/python3/stdlib_module/sqlite3/ProgrammingError
- tuts/python3/stdlib_module/sqlite3/register_adapter
- tuts/python3/stdlib_module/sqlite3/register_converter
- tuts/python3/stdlib_module/sqlite3/Row
- tuts/python3/stdlib_module/sqlite3/Time
- tuts/python3/stdlib_module/sqlite3/TimeFromTicks
- tuts/python3/stdlib_module/sqlite3/Timestamp
- tuts/python3/stdlib_module/sqlite3/TimestampFromTicks
- tuts/python3/stdlib_module/sqlite3/Warning
- tuts/python3/stdlib_module/sre_compile
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/tutorials/popular_application_domains/web_development_and_apis
Related notes
- tuts/python3/stdlib_module/copyreg Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dbm Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/marshal Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pickle Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/shelve Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/socketserver Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/sqlite3/adapt Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/sqlite3/Binary Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/sqlite3/Blob Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/sqlite3/complete_statement Linked here; links to this page; shared tags: #stdlib