Building db_utils.py
🏗️ Building db_utils.py
db_utils.py module used in production to populate the learning_blog database with course chapters. You'll see how everything from chapters 1-3 comes together: paths, configuration, database connections, error handling, and real-world SQL operations.
📋 Overview: What db_utils.py Does
The db_utils.py module provides database utility functions for:
- DatabaseConnection class — Connects to MySQL/MariaDB
- get_or_create_subtopic() — Find or create a course
- insert_chapter_with_content() — Insert a chapter and its HTML content
- rebuild_course() — Rebuild an entire course from chapters
It's used by rebuild_typescript_course.py to populate the database with generated course chapters.
📁 File Location
📦 Imports & Setup
mysql.connector— Database connection libraryError— Database error exception classdotenv— Load .env configurationtyping— Type hints for function parametersurllib.parse.quote— URL-encode strings for slug generation
🔌 DatabaseConnection Class
The core class that manages all database operations.
The __init__ Method
- Loads credentials from .env (not hard-coded)
- Sets sensible defaults (port=3306, charset=utf8mb4)
- Stores config for reuse across method calls
- Converts port string to integer
The connect() Method
The disconnect() Method
🔧 Helper Functions
generate_slug() Function
Convert a title into a URL-safe slug:
- Converts "Why TypeScript & Setup" → "why-typescript-setup"
- .lower() makes it lowercase
- .replace() converts spaces to hyphens
- quote() removes special characters
- Final loop removes double hyphens
💾 Core Database Functions
get_or_create_subtopic()
Find a course (subtopic) or create it if it doesn't exist:
- Checks if subtopic (course) already exists
- If exists: returns its ID
- If not: creates it and returns new ID
- Uses cursor.lastrowid to get the new ID
- Commits transaction if successful
- Rolls back if error occurs
insert_chapter_with_content()
Insert a chapter and its HTML content into the database:
🎯 Why This Pattern Works
- Separation of Concerns: DatabaseConnection handles connections, helper functions handle operations
- Parameterized Queries: All queries use %s placeholders (prevents SQL injection)
- Error Handling: Every database operation has try/except
- Transactions: Commit on success, rollback on error
- Resource Cleanup: finally blocks ensure cursors always close
- Type Hints: Return types are clear (int, bool, None, etc.)
- Configuration: All credentials come from .env, never hard-coded
📌 Common Patterns Used
| Pattern | Purpose | Example |
|---|---|---|
| Parameterized Query | Prevent SQL injection | cursor.execute("SELECT * FROM t WHERE id = %s", (id,)) |
| Check Before Insert | Avoid duplicates | SELECT first, then INSERT if not found |
| lastrowid | Get inserted row ID | page_id = cursor.lastrowid |
| Commit/Rollback | Transaction control | commit() on success, rollback() on error |
| try/except/finally | Error handling + cleanup | finally block always closes cursor |
🌍 Real-World Usage Example
💻 Coding Challenges
Challenge 1: Test db_utils.py Connection
Create a script that:
- Imports DatabaseConnection from db_utils
- Attempts to connect using credentials from .env
- Shows connection status and database info
- Safely closes the connection
Goal: Verify db_utils works with your database.
Challenge 2: Insert a Test Subtopic
Create a script that:
- Connects using db_utils
- Uses get_or_create_subtopic() to create a test course
- Shows the returned subtopic_id
- Calls it again to verify it returns the same ID (no duplicate)
Goal: Practice using db_utils helper functions.
Challenge 3: Complete Course Integration
Create a script that:
- Creates a test subtopic
- Inserts 3 test chapters with HTML content
- Verifies chapters are in database by querying them back
- Reports success with all IDs
Goal: Full database integration workflow.
🎯 What's Next
Chapter 5 shows how rebuild_typescript_course.py uses db_utils to automatically populate the database by reading generated HTML chapter files and inserting them with all the functions you've learned here.