Embedded file-backed storage
Small applications or scripts need local persistence without a database server.
Python · Module
Python's sqlite3 module provides a DB-API 2.0 interface for working with SQLite databases. It supports file-backed or in-memory databases and can also run as a simple SQLite shell.
The sqlite3 module provides Python's DB-API 2.0 interface to SQLite. Open a database with connect(), execute SQL through a connection or cursor, bind values with parameters, and use the connection as a context manager for transaction handling.
sqlite3.connect(database, timeout=5.0, detect_types=0, isolation_level='DEFERRED', check_same_thread=True, factory=sqlite3.Connection, cached_statements=128, uri=False)| Name | Type | Description |
|---|---|---|
database | str or path-like object | Database path or special database name such as ":memory:". |
timeout | float | Optional timeout in seconds before an OperationalError is raised when a table is locked. |
cached_statements | int | Optional number of statements cached internally for the connection. |
The sqlite3.connect() function returns a Connection object.
import sqlite3
with sqlite3.connect(":memory:") as connection:
connection.execute("CREATE TABLE items (name TEXT, quantity INTEGER)")
connection.execute("INSERT INTO items VALUES (?, ?)", ("notebook", 3))
rows = connection.execute("SELECT name, quantity FROM items").fetchall()
print(rows)Creates an in-memory database, inserts a parameterized row, queries it, and commits or rolls back automatically when the connection context ends.
Small applications or scripts need local persistence without a database server.
Tests need fast, isolated temporary data.
A script needs to inspect or modify SQLite data interactively.
sqlite3.connect() returns a Connection representing the database. SQL can be run with Connection.execute(), which creates and uses a cursor internally; explicit cursors are available when their methods or iteration are useful.
Follow-up: How should values be supplied safely? Use qmark or named placeholders and pass the values separately, rather than formatting them into the SQL string.
A connection context manager commits the transaction if the block completes normally and rolls it back if an exception leaves the block. It does not close the connection, so close it afterward or use an outer resource-management pattern.
Follow-up: What happens to an in-memory database after close()? Its data is lost because the database exists only for the lifetime of the connection.
The module follows Python's DB-API 2.0 interface and supports SQLite databases without a separate server process. A database file is created when connecting to a path that does not already exist.
Follow-up: How can sqlite3 be used without creating a Python script? Invoke it with the interpreter's -m switch to provide a simple SQLite shell.
ConnectionCursorsqlite3.connectsqlite3.Rowsqlite3.IntegrityErrorsqlite3.OperationalErrorDB-API 2.0PEP 249