Welcome to the Python Database Module. This directory provides a structured, educational, and production-ready collection of Python scripts demonstrating relational database interactions using both SQLite (Python standard library) and MySQL (external server connection driver).
If you are new to databases, this section will help you understand all fundamental concepts before writing code.
| Term | Definition | Analogous Concept |
|---|---|---|
| Database (DB) | An organized collection of structured data stored electronically on a computer system. | A digital filing cabinet or workbook. |
| Relational Database (RDBMS) | A database that organizes data into tables linked by predefined relationships. | Excel workbook with multiple interlinked sheets. |
| Table | A collection of related data entries organized in vertical columns and horizontal rows. | A single spreadsheet tab/sheet. |
| Column / Field | A vertical data attribute representing a specific type of information (e.g., name, age). |
A single spreadsheet column header. |
| Row / Record | A single horizontal data entry containing values for all attributes of an item. | A single spreadsheet row filled with data. |
| Primary Key (PK) | A unique identifier for every record in a table (e.g., id=101). No two rows can share the same PK. |
A Social Security Number or Student ID. |
| Foreign Key (FK) | A column in one table that references the Primary Key of another table to create a link between them. | A reference code pointing to another sheet. |
| SQL | Structured Query Language - The universal language used to communicate with relational databases. | The command language for database requests. |
| CRUD | Acronym for the 4 basic database operations: Create, Read, Update, and Delete. | Add, View, Edit, Remove operations. |
Databases enforce data types on each column to ensure data consistency and integrity.
| Data Type | SQL Keyword | Description | Python Equivalent | Example Values |
|---|---|---|---|---|
| Integer | INTEGER / INT |
Whole numbers (positive, negative, or zero). | int |
1, 42, -10, 2026 |
| Floating Point | REAL / FLOAT / DOUBLE |
Decimal numbers with fractional parts. | float |
19.99, 3.14159, -0.05 |
| Text / String | TEXT / VARCHAR(N) |
Text characters or strings. VARCHAR(N) limits string length to N. |
str |
"Alice", "Toyota Camry", "email@example.com" |
| Binary Data | BLOB |
Binary Large Object. Used for raw bytes like images or encrypted data. | bytes |
b'\x89PNG...' |
| Null Value | NULL |
Represents missing, empty, or unknown values. | None |
None |
Python includes the sqlite3 module by default. For external MySQL database management, follow the setup steps for your operating system below.
Press Win + R, type cmd or powershell, and press Enter.
:: Navigate to your project folder
cd C:\path\to\your\project\database
:: Create virtual environment named 'venv'
python -m venv venv
:: Activate virtual environment
venv\Scripts\activatepip install --upgrade pip
pip install -r requirements.txtcd /path/to/your/project/database
python3 -m venv venv
source venv/bin/activatepip install --upgrade pip
pip install -r requirements.txtcd /path/to/your/project/database
python3 -m venv venv
source venv/bin/activatepip install --upgrade pip
pip install -r requirements.txtTo guarantee code security, data integrity, and prevent regression bugs or SQL Injection vulnerabilities, an automated unit test suite is included in the tests/ directory.
- SQL Injection Defense: Tests tautology attacks (
' OR '1'='1), piggybackedDROP TABLEattempts, andUNIONquery injection payloads against all search functions to ensure parameters are properly bound. - SQLite Operations Test: Tests connection management, table creation, batch static insertion, dynamic user input handling, filtering, limit pagination, updates, and deletions in isolated temporary database instances (
tempfile). - MySQL Manager Test: Tests configuration validation, connection failure handling, fallback states, and mock query executions.
Run the full test suite using Python's built-in unittest runner:
python3 -m unittest discover -v -s testsOr using pytest:
pytest -v tests/database/
βββ README.md # Complete documentation, setup, and testing guide
βββ requirements.txt # External package dependencies (MySQL drivers, pytest)
βββ mysql_db.py # Object-oriented MySQL database manager
βββ tests/
β βββ __init__.py # Test package marker
β βββ test_sqlite_modules.py # SQLite CRUD operations test suite
β βββ test_mysql_manager.py # MySQLDatabaseManager test suite
β βββ test_security_sql_injection.py # Security & SQL Injection test suite
βββ sqlite_db/
βββ __init__.py # Package marker
βββ beginner_starter.py # Step-by-step beginner tutorial script
βββ connect_db.py # Connection and cursor initialization demo
βββ create_table.py # Table schema creation DDL demo
βββ insert_static_data.py # Static dataset batch insertion demo
βββ insert_dynamic_data.py # Dynamic user input record insertion demo
βββ read_all_data.py # Full table query (SELECT *) demo
βββ read_filtered_data.py # Conditional row query (WHERE) demo
βββ read_by_user_input.py # Dynamic single-parameter search demo
βββ read_by_multiple_inputs.py # Compound multi-parameter search demo
βββ read_with_limit.py # Pagination query (LIMIT) demo
βββ update_data.py # Record update (UPDATE) demo
βββ delete_data.py # Row deletion (DELETE) demo
βββ delete_data_with_commit.py # Persistent deletion with explicit commit demo
βββ email_counter_crud.py # Log aggregation CRUD counter demo
- Use Parameterized Queries: Always use
?(SQLite) or%s(MySQL) to pass variables safely and prevent SQL injection. - Always Use Context Managers: Use
with sqlite3.connect(...) as connection:to handle connection cleanup automatically. - Commit Transactions: DML commands (
INSERT,UPDATE,DELETE) requireconnection.commit()to persist changes to disk. - Run Unit Tests: Execute
python3 -m unittest discover -v -s testsbefore committing code changes.