⬅ Previous TopicRecursive Queries in SQL
Next Topic ⮕SQL with Java







SQL with Python
Connect, Query, and Automate School Data
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.
Why Use SQL with Python?
- Automate data entry and reporting
- 🔍 Query large datasets with SQL’s power
- 🤖 Build school applications like report cards, dashboards, or fee trackers
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())
Real-World School Use Cases
- Auto-inserting daily attendance from a CSV file
- 📑 Generating report cards and emailing them to parents
- Bulk importing exam scores
- Visualizing student performance using matplotlib + SQL
Best Practices
- Always close your DB connection with
conn.close()
- Use
try/except
for error handling - Never use plain strings to insert values — always parameterize
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.
QUIZ
Question 1:Which Python library is most commonly used to connect to SQL databases?
Question 2:You can execute SQL queries on a pandas DataFrame using SQLite syntax with the pandasql library.
Question 3:Which of the following are valid Python libraries or methods to execute SQL queries?
Question 4:What will be the output of the following Python code?
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("CREATE TABLE students (id INTEGER, name TEXT)")
c.execute("INSERT INTO students VALUES (1, 'Ravi')")
conn.commit()
c.execute("SELECT name FROM students")
print(c.fetchone()[0])
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("CREATE TABLE students (id INTEGER, name TEXT)")
c.execute("INSERT INTO students VALUES (1, 'Ravi')")
conn.commit()
c.execute("SELECT name FROM students")
print(c.fetchone()[0])