Introduction
What if your Python program could directly talk to your school database? Whether it’s fetching a student’s marks, generating reports, or inserting attendance records — integrating SQL with Python makes it possible. This tutorial shows how to use SQL inside Python using both SQLite and MySQL with real-life school examples.
Getting Started: SQLite with Python
Step 1: Import sqlite3
import sqlite3
Step 2: Connect to a database
conn = sqlite3.connect("school.db")
cursor = conn.cursor()
Step 3: Create a table
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
roll_no INTEGER PRIMARY KEY,
name TEXT,
class TEXT,
city TEXT
)
""")
conn.commit()
Step 4: Insert student data
cursor.execute("INSERT INTO students (roll_no, name, class, city) VALUES (?, ?, ?, ?)",
(1, 'Aarav', '10A', 'Pune'))
conn.commit()
Step 5: Query the data
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)
(1, 'Aarav', '10A', 'Pune')
Using MySQL with Python (via mysql-connector-python)
Step 1: Install package
pip install mysql-connector-python
Step 2: Connect to MySQL server
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = conn.cursor()
Step 3: Fetch student marks
cursor.execute("SELECT name, marks FROM marks WHERE subject = 'Maths'")
results = cursor.fetchall()
for name, marks in results:
print(f"{name} scored {marks} in Maths")
Aarav scored 90 in Maths
Diya scored 85 in Maths
Parameterized Queries to Avoid SQL Injection
name = "Aarav"
cursor.execute("SELECT * FROM students WHERE name = %s", (name,))
print(cursor.fetchall())
Summary
Integrating SQL with Python unlocks automation, analytics, and application building at a whole new level. Whether you’re building a student tracker or a dynamic marks dashboard, Python + SQL is a powerful duo — especially for managing and visualizing school data.
What’s Next?
Next: SQL Interview Questions — master real-world SQL scenarios and test your knowledge.

About the authorSrinivas Namala
Software Engineer
Srinivas focuses on backend development, databases, systems, and the technologies used to build reliable server-side applications.
View LinkedIn profile ↗