Sitemap
Hemraj Saini

Hemraj Saini

Python advance : SQL Connection

3 min readSep 24, 2025

--

Connecting Python with MySQL is a common task in many backend and data engineering workflows. But while most tutorials teach you how to connect and fetch data, very few focus on writing clean, modular, and production-ready code. In this post, we’ll walk through setting up a Python helper module that makes interacting with MySQL both easy and maintainable.

We’ll cover:

  • How to connect to a MySQL database using mysql-connector-python
  • Running basic CRUD operations (SELECT, INSERT, DELETE)
  • Using a contextmanager to manage DB resources
  • Logging function calls for easier debugging

Step 1: Setting Up MySQL Workbench

Before we get into code, make sure you have:

  • MySQL Server installed (port: 3306)
  • MySQL Workbench
  • A database named expense_manager with a table called expenses

If not, you can import a .sql file via Server > Data Import in Workbench and use the script provided in your project folder.

Make sure to note your DB credentials:

  • Host: localhost
  • User: root
  • Password: root
  • Port: 3306

📦 Step 2: Install the Required Python Package

pip install mysql-connector-python

🧱 Step 3: Creating a Modular DB Helper

Get Hemraj Saini’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s write a reusable DB helper using Python’s contextlib and a logging setup. This allows anyone to run queries without worrying about closing connections or committing transactions manually.

# db_helper.py
import mysql.connector
from contextlib import contextmanager
from logging_setup import setup_logger

logger = setup_logger('db_helper')

@contextmanager
def get_db_cursor(commit=False):
connection = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="expense_manager"
)
cursor = connection.cursor(dictionary=True)
yield cursor
if commit:
connection.commit()
cursor.close()
connection.close()

We’ve created a contextmanager that handles connection opening, closing, and optional commit. This saves you from forgetting connection.close() and connection.commit().

🔍 Step 4: CRUD Functions

✅ Fetch Expenses for a Specific Date

def fetch_expenses_for_date(expense_date):
logger.info(f"fetch_expenses_for_date called with {expense_date}")
with get_db_cursor() as cursor:
cursor.execute("SELECT * FROM expenses WHERE expense_date = %s", (expense_date,))
return cursor.fetchall()

➕ Insert a New Expense

def insert_expense(expense_date, amount, category, notes):
logger.info(f"Inserting: {expense_date}, {amount}, {category}, {notes}")
with get_db_cursor(commit=True) as cursor:
cursor.execute(
"INSERT INTO expenses (expense_date, amount, category, notes) VALUES (%s, %s, %s, %s)",
(expense_date, amount, category, notes)
)

🗑 Delete Expenses by Date

def delete_expenses_for_date(expense_date):
logger.info(f"Deleting expenses for {expense_date}")
with get_db_cursor(commit=True) as cursor:
cursor.execute("DELETE FROM expenses WHERE expense_date = %s", (expense_date,))

📊 Fetch Summary Grouped by Category

def fetch_expense_summary(start_date, end_date):
logger.info(f"Fetching summary from {start_date} to {end_date}")
with get_db_cursor() as cursor:
cursor.execute(
'''
SELECT category, SUM(amount) as total
FROM expenses
WHERE expense_date BETWEEN %s AND %s
GROUP BY category
''',
(start_date, end_date)
)
return cursor.fetchall()

🧪 Step 5: Running the Functions

You can run any of the above functions in a test script or directly from db_helper.py like this:

if __name__ == "__main__":
expenses = fetch_expenses_for_date("2024-09-30")
print(expenses)

insert_expense("2024-08-20", 75, "Groceries", "Bought veggies and fruits")

summary = fetch_expense_summary("2024-08-01", "2024-08-31")
for row in summary:
print(row)

delete_expenses_for_date("2024-08-20")

📌 Why Use a Context Manager?

If you’ve ever forgotten to close a DB connection, you know the pain. With @contextmanager, your connection and cursor are always cleaned up—automatically.

And with optional commit, you avoid unintentional writes during SELECT operations.

📚 Final Thoughts

This pattern helps build reliable data layers in Python without repeating boilerplate code for every query. It’s a clean, Pythonic approach that scales well across projects especially when your application grows.

If you’re building backend APIs, internal tools, or data pipelines, this modular setup will keep your code maintainable and safe.

--

--