Another Python SQLite Wrapper

3.53.0.0 · active · verified Fri Apr 10

APSW (Another Python SQLite Wrapper) is a comprehensive Python wrapper for the SQLite embedded relational database engine. It provides a thin, complete layer over the SQLite C API, staying up-to-date with both SQLite and Python. APSW offers extended functionality beyond the standard `sqlite3` module, including full text search, session, virtual tables, VFS, and advanced JSON support. It supports CPython 3.10 onwards and releases are approximately quarterly, mirroring SQLite's release cycle.

Warnings

Install

Imports

Quickstart

This example demonstrates how to establish a connection, apply best practices, create a table, insert data using positional and named bindings, and retrieve data. It uses a context manager for connection handling, which is the recommended approach.

import apsw
import os

db_file = 'example.db'
if os.path.exists(db_file):
    os.remove(db_file)

# Best practice application for optimal settings and error avoidance
apsw.bestpractice.apply(apsw.bestpractice.recommended)

# Use a context manager to ensure proper closing and transaction management
with apsw.Connection(db_file) as connection:
    cursor = connection.cursor()

    # Create a table
    cursor.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)")

    # Insert data
    cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ('Alice', 'alice@example.com'))
    cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ('Bob', 'bob@example.com'))

    # Select data
    print("All users:")
    for row in cursor.execute("SELECT id, name, email FROM users"):
        print(f"ID: {row[0]}, Name: {row[1]}, Email: {row[2]}")

    # Select with named bindings
    print("\nUser with ID 1:")
    for row in cursor.execute("SELECT name FROM users WHERE id = :id", {'id': 1}):
        print(f"Name: {row[0]}")

print(f"Database '{db_file}' operations complete.")

view raw JSON →