Below is a tiny, “batteries-included” wrapper around Python’s built-in sqlite3.
It gives you the exact six high-level calls you asked for, plus a couple of extras (type hints, auto-commit, auto-close, and a minimal CLI demo).
Save it as litecrud.py and run it directly to see it in action.
# litecrud.py
import sqlite3
from typing import Any, Dict, List, Optional, Tuple
class LiteCRUD:
"""
Very small, zero-dependency CRUD helper for SQLite.
"""
def __init__(self, db_path: str = ":memory:"):
self.db_path = db_path
self._conn: Optional[sqlite3.Connection] = None
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _open(self) -> sqlite3.Connection:
if self._conn is None:
self._conn = sqlite3.connect(self.db_path)
self._conn.row_factory = sqlite3.Row # dict-like rows
return self._conn
def _close(self) -> None:
if self._conn:
self._conn.close()
self._conn = None
def _execute(self, sql: str, params: Tuple[Any, ...] = ()) -> sqlite3.Cursor:
conn = self._open()
cur = conn.execute(sql, params)
conn.commit()
return cur
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def create_db_with_table(
self,
table: str,
schema: Dict[str, str],
primary_key: str = "id",
) -> None:
"""
Create a table if it does not exist.
Example schema: {"id": "INTEGER PRIMARY KEY", "name": "TEXT", "age": "INTEGER"}
"""
cols = ", ".join(f"{k} {v}" for k, v in schema.items())
sql = f"CREATE TABLE IF NOT EXISTS {table} ({cols})"
self._execute(sql)
def add_item(self, table: str, item: Dict[str, Any]) -> int:
"""
Insert a row and return the new primary key (lastrowid).
"""
cols = ", ".join(item.keys())
placeholders = ", ".join("?" * len(item))
sql = f"INSERT INTO {table} ({cols}) VALUES ({placeholders})"
cur = self._execute(sql, tuple(item.values()))
return cur.lastrowid
def get_item(self, table: str, pk: int, pk_col: str = "id") -> Optional[Dict[str, Any]]:
sql = f"SELECT * FROM {table} WHERE {pk_col} = ? LIMIT 1"
cur = self._execute(sql, (pk,))
row = cur.fetchone()
return dict(row) if row else None
def find_item(self, table: str, **where) -> List[Dict[str, Any]]:
"""
Find rows by exact column=value pairs.
Example: find_item("users", name="Alice", age=30)
"""
if not where:
return self.get_all_item(table)
cond = " AND ".join(f"{k} = ?" for k in where)
sql = f"SELECT * FROM {table} WHERE {cond}"
cur = self._execute(sql, tuple(where.values()))
return [dict(r) for r in cur.fetchall()]
def update_item(
self,
table: str,
pk: int,
updates: Dict[str, Any],
pk_col: str = "id",
) -> int:
"""
Update row(s) and return affected row count.
"""
if not updates:
return 0
set_clause = ", ".join(f"{k} = ?" for k in updates)
sql = f"UPDATE {table} SET {set_clause} WHERE {pk_col} = ?"
cur = self._execute(sql, (*updates.values(), pk))
return cur.rowcount
def get_all_item(self, table: str) -> List[Dict[str, Any]]:
cur = self._execute(f"SELECT * FROM {table}")
return [dict(r) for r in cur.fetchall()]
def get_page(
self,
table: str,
page_number: int = 1,
per_page: int = 10,
order_by: str = "id",
) -> List[Dict[str, Any]]:
"""
Simple offset/limit pagination.
"""
offset = (page_number - 1) * per_page
sql = f"""
SELECT * FROM {table}
ORDER BY {order_by}
LIMIT ? OFFSET ?
"""
cur = self._execute(sql, (per_page, offset))
return [dict(r) for r in cur.fetchall()]
# ------------------------------------------------------------------
# Context-manager sugar
# ------------------------------------------------------------------
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._close()
# ----------------------------------------------------------------------
# Quick demo / self-test
# ----------------------------------------------------------------------
if __name__ == "__main__":
with LiteCRUD("demo.db") as db:
# 1. Create table
db.create_db_with_table(
"users",
{
"id": "INTEGER PRIMARY KEY",
"name": "TEXT NOT NULL",
"age": "INTEGER",
},
)
# 2. Add some users
alice_id = db.add_item("users", {"name": "Alice", "age": 30})
bob_id = db.add_item("users", {"name": "Bob", "age": 25})
# 3. Retrieve
print("Alice:", db.get_item("users", alice_id))
print("All users:", db.get_all_item("users"))
# 4. Find
print("Find Bob:", db.find_item("users", name="Bob"))
# 5. Update
db.update_item("users", bob_id, {"age": 26})
print("Bob after update:", db.get_item("users", bob_id))
# 6. Pagination
for i in range(10):
db.add_item("users", {"name": f"User{i}", "age": 20 + i})
print("Page 2 (2 per page):", db.get_page("users", page_number=2, per_page=2))
How to use in your own code
from litecrud import LiteCRUD
db = LiteCRUD("my_app.db")
# one-time setup
db.create_db_with_table(
"products",
{
"id": "INTEGER PRIMARY KEY",
"title": "TEXT",
"price": "REAL",
"stock": "INTEGER",
},
)
# CRUD away
product_id = db.add_item("products", {"title": "Keyboard", "price": 49.99, "stock": 10})
print(db.get_item("products", product_id))
That’s it—copy, paste, and start building.