# Python SQLite libraries

Python SQLite libraries read and write SQLite database files from Python code, beyond the sqlite3 module in the standard library. A library either adds an ORM or query layer or exposes the SQLite C API more directly than the standard module does. These libraries let desktop apps, test suites, and AI agents keep structured local data without a database server.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [SQLAlchemy](#sqlalchemy) | 417.4M | 12.3K | Nov 2026 | MIT |
| [aiosqlite](#aiosqlite) | 74.3M | 1.6K | Dec 2025 | MIT |
| [Peewee](#peewee) | 42.4M | 12.0K | Oct 2026 | MIT |
| [SQLModel](#sqlmodel) | 28.1M | 18.6K | Nov 2026 | MIT |
| [APSW](#apsw) | 2.6M | 955 | Oct 2026 | any-OSI |
| [sqlite-utils](#sqlite-utils) | 1.1M | 2.2K | Aug 2026 | Apache-2.0 |
| [pysqlite3-binary](#pysqlitethree-binary) | 798.1K | 246 | Dec 2025 | zlib/libpng |
| [sqlcipher3](#sqlcipherthree) | 465.6K | 127 | Nov 2026 | Zlib |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[SQLAlchemy](#sqlalchemy) has the most monthly downloads in this comparison, at 417.4M, a count that covers all its database work.

## Capabilities

| Library | ORM model classes | AsyncIO query interface |
| --- | --- | --- |
| [SQLAlchemy](#sqlalchemy) | Yes | Via plugin |
| [aiosqlite](#aiosqlite) | No | Yes |
| [Peewee](#peewee) | Yes | Via plugin |
| [SQLModel](#sqlmodel) | Yes | Via plugin |
| [APSW](#apsw) | Yes | Yes |
| [sqlite-utils](#sqlite-utils) | No | No |
| [pysqlite3-binary](#pysqlitethree-binary) | No | No |
| [sqlcipher3](#sqlcipherthree) | No | No |

## Libraries

### SQLAlchemy

[GitHub](https://github.com/sqlalchemy/sqlalchemy) · [PyPI](https://pypi.org/project/sqlalchemy) · [Docs](https://docs.sqlalchemy.org/en/21/tutorial/dbapi_transactions.html)

Provides a database abstraction library.

- Downloads / mo: 417.4M
- Stars: 12.3K
- Last release: 2.1.9
- License: MIT
- Capabilities: [From the SQLAlchemy docs](https://docs.sqlalchemy.org/en/21/tutorial/dbapi_transactions.html)

```sh
pip install SQLAlchemy
```

**PrefectHQ/prefect** (24.2K stars)

[PrefectHQ/prefect](https://github.com/PrefectHQ/prefect) 

```python
def begin_sqlite_stmt(self, conn: sa.Connection) -> None:
    # emit our own BEGIN
    # requires `begin_sqlite_conn`
    # see https://docs.sqlalchemy.org/en/20/dialects/sqlite.html#serializable-isolation-savepoints-transactional-ddl
    mode = SQLITE_BEGIN_MODE.get()
    if mode is not None:
        conn.exec_driver_sql(f"BEGIN {mode}")

```

[src/prefect/server/database/configurations.py](https://github.com/PrefectHQ/prefect/blob/ec4b188a19371cb79bc91afe897042bca3a3c95f/src/prefect/server/database/configurations.py#L594-L600) · [More projects using SQLAlchemy →](https://dashboard.exa.ai/playground/search?q=sqlalchemy%20GitHub%20projects)

**Quickstart**

```python
from sqlalchemy import create_engine, text
engine = create_engine("sqlite+pysqlite:///:memory:")
with engine.connect() as connection:
    print(connection.execute(text("SELECT 1")).scalar())

```

From [dbapi_transactions.html](https://docs.sqlalchemy.org/en/21/tutorial/dbapi_transactions.html)

### aiosqlite

[GitHub](https://github.com/omnilib/aiosqlite) · [PyPI](https://pypi.org/project/aiosqlite) · [Docs](https://aiosqlite.omnilib.dev/en/stable/)

Bridges asyncio code to the standard sqlite3 module.

- Downloads / mo: 74.3M
- Stars: 1.6K
- Last release: 0.22.1
- License: MIT
- Capabilities: [From the aiosqlite docs](https://aiosqlite.omnilib.dev/en/stable/)

```sh
pip install aiosqlite
```

**langchain-ai/langgraph** (45.1K stars)

[langchain-ai/langgraph](https://github.com/langchain-ai/langgraph) 

```python
async def setup(self) -> None:
    """Set up the checkpoint database asynchronously.

    This method creates the necessary tables in the SQLite database if they don't
    already exist. It is called automatically when needed and should not be called
    directly by the user.
    """
    async with self.lock:
        if self.is_setup:
            return
        await _ensure_connected(self.conn)
        async with self.conn.executescript(
            """
            PRAGMA journal_mode=WAL;
            CREATE TABLE IF NOT EXISTS checkpoints (
                thread_id TEXT NOT NULL,
                checkpoint_ns TEXT NOT NULL DEFAULT '',
                checkpoint_id TEXT NOT NULL,
                parent_checkpoint_id TEXT,
                type TEXT,
                checkpoint BLOB,
                metadata BLOB,
                PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id)
            );
            CREATE TABLE IF NOT EXISTS writes (
                thread_id TEXT NOT NULL,
                checkpoint_ns TEXT NOT NULL DEFAULT '',
                checkpoint_id TEXT NOT NULL,
                task_id TEXT NOT NULL,
                task_path TEXT NOT NULL DEFAULT '',
                idx INTEGER NOT NULL,
                channel TEXT NOT NULL,
                type TEXT,
                value BLOB,
                PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
            );
            """
        ):
            await self.conn.commit()

        # sqlite has no ADD COLUMN IF NOT EXISTS; this migrates databases
        # created before `task_path` existed and is a no-op on the rest.
        try:
            await self.conn.execute(
                "ALTER TABLE writes ADD COLUMN task_path TEXT NOT NULL DEFAULT ''"
            )
            await self.conn.commit()
        except aiosqlite.OperationalError as e:
            # A read-only database from before the column can still be read;
            # its rows would all read back as '' anyway.
            if "readonly database" in str(e):
                self._has_task_path = False
            elif "duplicate column name" not in str(e):
                raise

        self.is_setup = True

```

[libs/checkpoint-sqlite/langgraph/checkpoint/sqlite/aio.py](https://github.com/langchain-ai/langgraph/blob/7830b91a24e657a8167e2dbf40c3fa5a77ef5d93/libs/checkpoint-sqlite/langgraph/checkpoint/sqlite/aio.py#L317-L372) · [More projects using aiosqlite →](https://dashboard.exa.ai/playground/search?q=aiosqlite%20GitHub%20projects)

**Quickstart**

```python
import asyncio
import aiosqlite
async def main():
    async with aiosqlite.connect(":memory:") as db:
        async with db.execute("SELECT 1") as cursor:
            print(await cursor.fetchone())
asyncio.run(main())

```

From [index.html](https://aiosqlite.omnilib.dev/en/stable/)

### Peewee

[GitHub](https://github.com/coleifer/peewee) · [PyPI](https://pypi.org/project/peewee) · [Docs](https://docs.peewee-orm.com/en/latest/peewee/api.html)

Maps Python models and query expressions to SQLite tables and SQL.

- Downloads / mo: 42.4M
- Stars: 12.0K
- Last release: 4.5.3
- License: MIT
- Capabilities: [From the Peewee docs](https://docs.peewee-orm.com/en/latest/peewee/api.html)

**Strengths**

- **Models express related SQLite tables.** Declare model fields and foreign keys for related records.
- **Configures SQLite connection pragmas.** Set journal mode and foreign-key enforcement when constructing SqliteDatabase.

**Watch out for**

- **Async SQLite needs another driver.** Install aiosqlite when using AsyncSqliteDatabase.
- **In-memory async databases share connections.** Pool size does not add connections to an in-memory database.

```sh
pip install peewee
```

**coleifer/sqlite-web** (4.2K stars)

[coleifer/sqlite-web](https://github.com/coleifer/sqlite-web) 

```python
def initialize_dataset(filename):
    dataset_kw = {}
    if peewee_version >= (3, 14, 9):
        dataset_kw['include_views'] = True

    if dataset_config['read_only']:
        if peewee_version < (3, 5, 1):
            die('Peewee 3.5.1 or newer is required for read-only access.')
        db = SqliteDatabase('file:%s?mode=ro' % filename, uri=True)
        try:
            db.connect()
        except OperationalError:
            die('Unable to open database file in read-only mode. Ensure that '
                'the database exists in order to use read-only mode.')
        db.close()
    else:
        db = SqliteDatabase(filename)

    if dataset_config['foreign_keys']:
        db.pragma('foreign_keys', True, permanent=True)

    if dataset_config['extensions']:
        # Load extensions before performing introspection.
        for ext in dataset_config['extensions']:
            db.load_extension(ext)

    if dataset_config['startup_hook']:
        dataset_config['startup_hook'](db)

    dataset = SqliteDataSet(db, **dataset_kw)
    dataset.ensure_cache()
    dataset.close()
    return dataset

```

[sqlite_web/sqlite_web.py](https://github.com/coleifer/sqlite-web/blob/8c72947e63d6363f7b090801965e8321200283ba/sqlite_web/sqlite_web.py#L1879-L1911) · [More projects using Peewee →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20peewee%20for%20SQLite%20backups%20checkpoint%20persistence%20schema%20migrations%20and%20database%20introspection&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from peewee import SqliteDatabase
db = SqliteDatabase(":memory:")
print(db.execute_sql("SELECT 1").fetchone())
db.close()

```

From [quickstart.html](https://docs.peewee-orm.com/en/latest/peewee/api.html)

### SQLModel

[GitHub](https://github.com/fastapi/sqlmodel) · [PyPI](https://pypi.org/project/sqlmodel) · [Docs](https://sqlmodel.tiangolo.com/tutorial/select/)

Works with SQL databases in Python.

- Downloads / mo: 28.1M
- Stars: 18.6K
- Last release: 0.0.50
- License: MIT
- Capabilities: [From the SQLModel docs](https://sqlmodel.tiangolo.com/tutorial/select/)

```sh
pip install sqlmodel
```

**fastapi/fastapi** (104.8K stars)

[fastapi/fastapi](https://github.com/fastapi/fastapi) 

```python
@app.get("/heroes/")
def read_heroes(
    session: SessionDep,
    offset: int = 0,
    limit: Annotated[int, Query(le=100)] = 100,
) -> list[Hero]:
    heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
    return heroes

```

[docs_src/sql_databases/tutorial001.py](https://github.com/fastapi/fastapi/blob/05e6df7e906c3decba377c37548019973f40bf15/docs_src/sql_databases/tutorial001.py#L48-L55) · [More projects using SQLModel →](https://dashboard.exa.ai/playground/search?q=sqlmodel%20GitHub%20projects)

**Quickstart**

```python
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Hero(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str
engine = create_engine("sqlite:///:memory:")
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
    print(session.exec(select(Hero)).all())

```

From [README.md](https://sqlmodel.tiangolo.com/tutorial/create-db-and-table/)

### APSW

[GitHub](https://github.com/rogerbinns/apsw) · [PyPI](https://pypi.org/project/apsw) · [Docs](https://rogerbinns.github.io/apsw/connection.html)

Connects Python to SQLite’s complete C API, including async operation.

- Downloads / mo: 2.6M
- Stars: 955
- Last release: 3.54.1.0
- License: any-OSI
- Capabilities: [From the APSW docs](https://rogerbinns.github.io/apsw/connection.html)

**Strengths**

- **Exposes SQLite-specific extension APIs.** Access virtual tables, file-system hooks, backups, and tracing.
- **Includes awaitable connection operations.** Use async mode to await SQLite work on dedicated connection threads.

**Watch out for**

- **Shared connections serialize database work.** Use multiple connections when database operations need concurrency.
- **Mixed SQLite builds need care.** On non-Windows systems, avoid mixing SQLite builds on one database in one process.

```sh
pip install apsw
```

**kovidgoyal/calibre** (26.5K stars)

[kovidgoyal/calibre](https://github.com/kovidgoyal/calibre) 

```python
def _backup_database(self, path: str, name: str, extra_sql: str = '', num_of_retries: int = 10, busy_timeout: float = 60) -> None:
    for retry_count in range(num_of_retries):
        try:
            with closing(apsw.Connection(path)) as dest_db:
                with dest_db.backup('main', self.conn, name) as b:
                    busy_since = None
                    while not b.done:
                        try:
                            b.step(128)
                        except apsw.BusyError as e:
                            # Locks on some filesystems such as SMB/CIFS
                            # shares never succeed, so dont retry forever
                            now = time.monotonic()
                            if busy_since is None:
                                busy_since = now
                            elif now - busy_since > busy_timeout:
                                raise apsw.BusyError(
                                    f'Could not lock the database at {path} for {busy_timeout} seconds.'
                                    ' The filesystem it is on probably does not support file locking.'
                                ) from e
                            time.sleep(0.05)
                        else:
                            busy_since = None
                if extra_sql:
                    dest_db.cursor().execute(extra_sql)
            return
        except apsw.IOError as e:
            # backup step() can fail transiently, either with
            # SQLITE_IOERR_SHORT_READ when the source database is modified
            # while it is being read, or with a plain SQLITE_IOERR and no
            # error message set on the connection, which apsw reports as
            # "not an error". Once step() fails the backup object is dead,
            # so restart the entire backup. Any other extended result code
            # is a genuine I/O error, and is not retried.
            if retry_count >= num_of_retries - 1 or getattr(e, 'extendedresult', None) not in (apsw.SQLITE_IOERR, apsw.SQLITE_IOERR_SHORT_READ):
                raise
            with suppress(OSError):
                os.remove(path)
            time.sleep(0.2)

```

[src/calibre/db/backend.py](https://github.com/kovidgoyal/calibre/blob/8d119ee9e310918c3693200a9b357bdc98b5884d/src/calibre/db/backend.py#L3326-L3364) · [More projects using APSW →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20apsw%20for%20SQLite%20backups%20checkpoint%20persistence%20schema%20migrations%20and%20database%20introspection&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import apsw
with apsw.Connection(":memory:") as connection:
    print(connection.execute("SELECT 1").fetchone())

```

From [pysqlite.html](https://rogerbinns.github.io/apsw/connection.html)

### sqlite-utils

[GitHub](https://github.com/simonw/sqlite-utils) · [PyPI](https://pypi.org/project/sqlite-utils) · [Docs](https://sqlite-utils.datasette.io/en/stable/python-api.html)

Provides Python APIs and command-line tools for manipulating SQLite data and schemas.

- Downloads / mo: 1.1M
- Stars: 2.2K
- Last release: 4.2.1
- License: Apache-2.0
- Capabilities: [From the sqlite-utils docs](https://sqlite-utils.datasette.io/en/stable/python-api.html)

**Strengths**

- **Creates tables when inserting records.** Insert dictionaries without separately declaring the table first.
- **Registers Python SQL functions.** Register a Python function for use inside SQL queries.

**Watch out for**

- **Write calls commit separately.** Use db.atomic when several writes must succeed or fail together.

```sh
pip install sqlite-utils
```

**simonw/llm** (12.8K stars)

[simonw/llm](https://github.com/simonw/llm) 

```python
@migration
def m014_schemas(db):
    db["schemas"].create(
        {
            "id": str,
            "content": str,
        },
        pk="id",
    )
    db["responses"].add_column("schema_id", str, fk="schemas", fk_col="id")
    # Clean up SQL create table indentation
    db["responses"].transform()
    # These changes may have dropped the FTS configuration, fix that
    db["responses"].enable_fts(
        ["prompt", "response"], create_triggers=True, replace=True
    )

```

[llm/migrations.py](https://github.com/simonw/llm/blob/2216eb1446cf74b93da7ef0f107d2c1982fd611e/llm/migrations.py#L241-L256) · [More projects using sqlite-utils →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20sqlite-utils%20for%20SQLite%20backups%20checkpoint%20persistence%20schema%20migrations%20and%20database%20introspection&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from sqlite_utils import Database
db = Database(memory=True)
print(db.execute("SELECT 1").fetchone())

```

From [python-api.html](https://sqlite-utils.datasette.io/en/stable/python-api.html)

### pysqlite3-binary

[GitHub](https://github.com/coleifer/pysqlite3) · [PyPI](https://pypi.org/project/pysqlite3-binary)

Implements the DB-API interface for SQLite.

- Downloads / mo: 798.1K
- Stars: 246
- Last release: 0.5.4.post2
- License: zlib/libpng
- Capabilities: [From the pysqlite3-binary docs](https://github.com/coleifer/pysqlite3)

```sh
pip install pysqlite3-binary
```

**simonw/sqlite-utils** (2.2K stars)

[simonw/sqlite-utils](https://github.com/simonw/sqlite-utils) 

```python
def __init__(
    self,
    filename_or_conn: str | pathlib.Path | sqlite3.Connection | None = None,
    memory: bool = False,
    memory_name: str | None = None,
    recreate: bool = False,
    recursive_triggers: bool = True,
    tracer: Tracer | None = None,
    use_counts_table: bool = False,
    execute_plugins: bool = True,
    use_old_upsert: bool = False,
    strict: bool = False,
):
    self.memory_name = None
    self.memory = False
    self.use_old_upsert = use_old_upsert
    if not (
        (filename_or_conn is not None and (not memory and not memory_name))
        or (filename_or_conn is None and (memory or memory_name))
    ):
        raise ValueError("Either specify a filename_or_conn or pass memory=True")
    if memory_name:
        uri = f"file:{memory_name}?mode=memory&cache=shared"
        self.conn = sqlite3.connect(
            uri,
            uri=True,
            check_same_thread=False,
        )
        self.memory = True
        self.memory_name = memory_name
    elif memory or filename_or_conn == ":memory:":
        self.conn = sqlite3.connect(":memory:")
        self.memory = True
    elif isinstance(filename_or_conn, (str, pathlib.Path)):
        if recreate and os.path.exists(filename_or_conn):
            try:
                os.remove(filename_or_conn)
            except OSError:
                # Avoid mypy and __repr__ errors, see:
                # https://github.com/simonw/sqlite-utils/issues/503
                self.conn = sqlite3.connect(":memory:")
                raise
        self.conn = sqlite3.connect(str(filename_or_conn))
    else:
        if recreate:
            raise ValueError("recreate cannot be used with connections, only paths")
        self.conn = cast(sqlite3.Connection, filename_or_conn)
        # Python 3.12+ autocommit=True/False connections make commit()
        # and rollback() behave differently, silently breaking the
        # transaction handling used by every write method
        autocommit = getattr(self.conn, "autocommit", None)
        if autocommit is not None and autocommit != getattr(
            sqlite3, "LEGACY_TRANSACTION_CONTROL", -1
        ):
            raise TransactionError(
                "sqlite-utils requires a connection that uses the default "
                "transaction handling - connections created with "
                "autocommit=True or autocommit=False are not supported"
            )
    self._tracer: Tracer | None = tracer
    if recursive_triggers:
        self.execute("PRAGMA recursive_triggers=on;")
    self._registered_functions: set = set()
    self.use_counts_table = use_counts_table
    if execute_plugins:
        ensure_plugins_loaded()
        pm.hook.prepare_connection(conn=self.conn)
    self.strict = strict

```

[sqlite_utils/db.py](https://github.com/simonw/sqlite-utils/blob/9c66bafa52ae23d40499c74b0db3b635bcddb876/sqlite_utils/db.py#L569-L636) · [More projects using pysqlite3-binary →](https://dashboard.exa.ai/playground/search?q=pysqlite3-binary%20GitHub%20projects)

**Quickstart**

```python
from pysqlite3 import dbapi2
connection = dbapi2.connect(":memory:")
connection.execute("CREATE TABLE demo (id INTEGER PRIMARY KEY)")
connection.close()

```

From [README.md](https://github.com/coleifer/pysqlite3/blob/master/pysqlite3/dbapi2.py)

### sqlcipher3

[GitHub](https://github.com/coleifer/sqlcipher3) · [PyPI](https://pypi.org/project/sqlcipher3) · [Docs](https://github.com/coleifer/sqlcipher3/blob/master/README.md)

Implements the DB-API interface for SQLCipher.

- Downloads / mo: 465.6K
- Stars: 127
- Last release: 0.6.5
- License: Zlib
- Capabilities: [From the sqlcipher3 docs](https://github.com/coleifer/sqlcipher3/blob/master/README.md)

```sh
pip install sqlcipher3
```

**coleifer/peewee** (12.0K stars)

[coleifer/peewee](https://github.com/coleifer/peewee) 

```python
def _connect(self):
    params = dict(self.connect_params)
    passphrase = params.pop('passphrase', '').replace("'", "''")

    conn = sqlcipher.connect(self.database, isolation_level=None, **params)
    try:
        if passphrase:
            conn.execute("PRAGMA key='%s'" % passphrase)
        self._add_conn_hooks(conn)
    except:
        conn.close()
        raise
    return conn

```

[playhouse/sqlcipher_ext.py](https://github.com/coleifer/peewee/blob/a832f70cf46d581dd2d87ac713e1dcbef364c25a/playhouse/sqlcipher_ext.py#L36-L48) · [More projects using sqlcipher3 →](https://dashboard.exa.ai/playground/search?q=sqlcipher3%20GitHub%20projects)

**Quickstart**

```python
from sqlcipher3 import dbapi2
connection = dbapi2.connect(":memory:")
connection.execute("PRAGMA key='replace-with-a-secret'")
connection.execute("CREATE TABLE demo (id INTEGER PRIMARY KEY)")
connection.close()

```

From [README.md](https://github.com/coleifer/sqlcipher3/blob/master/sqlcipher3/dbapi2.py)

## FAQ

### Which Python SQLite library should I use?

The standard library's sqlite3 module covers direct SQL. [SQLAlchemy](#sqlalchemy) and [Peewee](#peewee) suit applications that want an ORM over SQLite. [aiosqlite](#aiosqlite) suits asyncio code. [APSW](#apsw) suits code that needs the full SQLite C API, such as online backups.

### What is Peewee?

[Peewee](#peewee) is a small ORM with models, queries, and SQLite database helpers. It also has a separate asyncio API.

### Which SQLite interface comes with Python?

The sqlite3 module exposes SQLite through the standard library. It ships with Python and needs no install.

### What is SQLModel?

[SQLModel](#sqlmodel) defines database tables as Pydantic-backed model classes that work with SQLAlchemy.

### What is aiosqlite?

[aiosqlite](#aiosqlite) is an asyncio bridge to the standard sqlite3 module. It runs database operations on a dedicated worker thread per connection. Code awaits each result.

### What is APSW?

[APSW](#apsw) is a Python wrapper for the SQLite C API, with incremental backups and built-in async operation.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python SQLite libraries sqlite3 APSW sqlite-utils Peewee code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
