.
---
📘 PROGRAM – 1
Heading: Create Database and Students Table
Aim:
To connect Python with MySQL and create a database school_db and table students.
import [Link]
conn = [Link](
host='localhost',
user='root',
password='12345'
)
cursor = [Link]()
[Link]("CREATE DATABASE IF NOT EXISTS school_db")
[Link]("USE school_db")
[Link]("""
CREATE TABLE IF NOT EXISTS students (
roll_no INT PRIMARY KEY,
name VARCHAR(100),
class VARCHAR(10),
age INT
)
""")
print("Database and students table created successfully.")
[Link]()
[Link]()
---
📘 PROGRAM – 2
Heading: Insert Student Records and Display All
Aim:
To insert student data into the students table and display all records.
import [Link]
data = [
(1, 'Asha Kumar', '12-A', 17),
(2, 'Rahul Verma', '12-A', 18),
(3, 'Sana Reddy', '12-B', 17)
]
conn = [Link](
host='localhost',
user='root',
password='12345',
database='school_db'
)
cursor = [Link]()
query = "INSERT INTO students (roll_no, name, class, age) VALUES (%s, %s, %s, %s)"
for row in data:
try:
[Link](query, row)
except [Link]:
pass
[Link]()
[Link]("SELECT * FROM students ORDER BY roll_no")
for r in [Link]():
print(r)
[Link]()
[Link]()
---
📘 PROGRAM – 3
Heading: Update and Delete Student Records
Aim:
To update a student's class and delete a student record using Python and MySQL.
import [Link]
conn = [Link](
host='localhost',
user='root',
password='12345',
database='school_db'
)
cursor = [Link]()
[Link]("UPDATE students SET class = '12-A' WHERE roll_no = 3")
[Link]("DELETE FROM students WHERE roll_no = 2")
[Link]()
[Link]("SELECT * FROM students")
for r in [Link]():
print(r)
[Link]()
[Link]()
---
📘 PROGRAM – 4
Heading: Count Students in Each Class (Using GROUP BY)
Aim:
To count the number of students in each class using GROUP BY.
import [Link]
conn = [Link](
host='localhost',
user='root',
password='12345',
database='school_db'
)
cursor = [Link]()
[Link]("SELECT class, COUNT(*) FROM students GROUP BY class")
print("Class\tCount")
for row in [Link]():
print(row[0], "\t", row[1])
[Link]()
[Link]()
---
📘 PROGRAM – 5
Heading: Display Students Ordered by Name (Using ORDER BY)
Aim:
To display all student records sorted alphabetically by name using ORDER BY.
import [Link]
conn = [Link](
host='localhost',
user='root',
password='12345',
database='school_db'
)
cursor = [Link]()
[Link]("SELECT roll_no, name, class, age FROM students ORDER BY name
ASC")
print("Roll\tName\t\tClass\tAge")
for row in [Link]():
print(row[0], "\t", row[1], "\t", row[2], "\t", row[3])
[Link]()
[Link]()