How to Create a Database Helper Class for Beginners in Python

Build a beginner-friendly SQLite helper class with indexing and batch inserts to optimize database queries in Python.

Easy Python 3.9+ Aug 9, 2026 Database scaling & optimization 13 views 0 copies

Python code

47 lines
Python 3.9+
import sqlite3


class DatabaseHelper:
    def __init__(self, db_path):
        self.connection = sqlite3.connect(db_path)
        self.cursor = self.connection.cursor()

    def create_table_with_index(self, table_name, columns, indexed_column):
        columns_sql = ", ".join(f"{name} {dtype}" for name, dtype in columns)
        self.cursor.execute(f"CREATE TABLE IF NOT EXISTS {table_name} ({columns_sql})")
        self.cursor.execute(f"CREATE INDEX IF NOT EXISTS idx_{table_name}_{indexed_column} ON {table_name} ({indexed_column})")
        self.connection.commit()

    def insert_many_optimized(self, table_name, data):
        placeholders = ", ".join("?" * len(data[0]))
        self.cursor.executemany(f"INSERT INTO {table_name} VALUES ({placeholders})", data)
        self.connection.commit()

    def query_with_index(self, table_name, indexed_column, value):
        self.cursor.execute(f"SELECT * FROM {table_name} WHERE {indexed_column} = ?", (value,))
        return self.cursor.fetchall()

    def close(self):
        self.connection.close()


if __name__ == "__main__":
    db = DatabaseHelper("scaling_example.db")

    db.create_table_with_index(
        "users",
        [("id", "INTEGER PRIMARY KEY"), ("name", "TEXT"), ("age", "INTEGER")],
        indexed_column="age"
    )

    sample_data = [
        (1, "Alice", 30),
        (2, "Bob", 25),
        (3, "Charlie", 35)
    ]
    db.insert_many_optimized("users", sample_data)

    results = db.query_with_index("users", "age", 25)
    print("Optimized query result:", results)

    db.close()

Output

stdout
Optimized query result: [(2, 'Bob', 25)]

How it works

The DatabaseHelper class wraps common SQLite operations into reusable methods, making it easy for beginners to work with databases. The create_table_with_index method creates both a table and an index on a specified column, which speeds up WHERE queries. Using executemany for batch inserts reduces Python-to-SQLite round trips, improving performance for large datasets. Prepared statements with ? placeholders prevent SQL injection when using user input. The close method ensures the database connection is properly released when done.

Common mistakes

  • Forgetting to call `commit` after inserts or creates, leaving changes unpersisted
  • Using string formatting for query values instead of parameterized `?` placeholders, risking SQL injection
  • Indexing every column, which slows down writes without meaningful read benefits
  • Not closing the connection, causing resource leaks in long-running applications

Variations

  1. Use `sqlite3.Row` as the row factory to access columns by name instead of index
  2. Wrap methods in `with` statements using `contextlib.closing` to auto-close connections

Real-world use cases

  • Powering a small web app that needs fast lookups on a user table by age or email.
  • Batch-loading thousands of sensor readings into a local analytics database.
  • Creating an in-house admin tool that queries a product catalog with indexed filters.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Database scaling & optimization

Related tutorials and quizzes for this topic.