⬅ Previous Topic
Recursive Queries in SQLNext Topic ⮕
SQL with Java⬅ Previous Topic
Recursive Queries in SQLNext Topic ⮕
SQL with JavaWhat 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.
import sqlite3
conn = sqlite3.connect("school.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
roll_no INTEGER PRIMARY KEY,
name TEXT,
class TEXT,
city TEXT
)
""")
conn.commit()
cursor.execute("INSERT INTO students (roll_no, name, class, city) VALUES (?, ?, ?, ?)",
(1, 'Aarav', '10A', 'Pune'))
conn.commit()
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)
(1, 'Aarav', '10A', 'Pune')
mysql-connector-python
)
pip install mysql-connector-python
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="school"
)
cursor = conn.cursor()
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
name = "Aarav"
cursor.execute("SELECT * FROM students WHERE name = %s", (name,))
print(cursor.fetchall())
conn.close()
try/except
for error handlingIntegrating 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.
Next: SQL Interview Questions — master real-world SQL scenarios and test your knowledge.
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])
⬅ Previous Topic
Recursive Queries in SQLNext Topic ⮕
SQL with JavaYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.