0% found this document useful (0 votes)
0 views5 pages

Python MySQL Operation Exercies Solutions

The document outlines a series of tasks to manage a MySQL database for a school, including creating a database and table, connecting to the database, and performing CRUD operations on student records. It provides Python scripts for inserting, fetching, updating, deleting, searching, paginating, counting records, and backing up/restoring data to/from CSV files. Additionally, it suggests combining these functionalities into a menu-driven program for user interaction.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views5 pages

Python MySQL Operation Exercies Solutions

The document outlines a series of tasks to manage a MySQL database for a school, including creating a database and table, connecting to the database, and performing CRUD operations on student records. It provides Python scripts for inserting, fetching, updating, deleting, searching, paginating, counting records, and backing up/restoring data to/from CSV files. Additionally, it suggests combining these functionalities into a menu-driven program for user interaction.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Setup

1. Create a Sample Database and Table:

CREATE DATABASE school;

USE school;

CREATE TABLE students (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT,
grade VARCHAR(5)
);

Assignments

1. Create a Connection

Write a Python script to connect to the MySQL server and the school database. Print a success
message if the connection is established.

Hints:

 Use mysql.connector.connect.
 Handle connection errors using try...except.

import mysql.connector

try:
connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="school"
)
if connection.is_connected():
print("Connected to MySQL")
except mysql.connector.Error as e:
print("Error connecting to MySQL:", e)
finally:
if connection.is_connected():
connection.close()

2. Insert Records into the Table

Write a script to insert a list of student records into the students table.

Sample Data:
students = [
("John Doe", 16, "10th"),
("Jane Smith", 17, "11th"),
("Mike Johnson", 15, "9th")
]

Hints:

 Use cursor.execute for a single record or cursor.executemany for multiple records.


 Commit the transaction.

def insert_students(connection, students):


cursor = connection.cursor()
sql = "INSERT INTO students (name, age, grade) VALUES (%s, %s, %s)"
cursor.executemany(sql, students)
connection.commit()
print(f"{cursor.rowcount} students inserted.")

3. Fetch and Display All Records

Write a script to fetch all records from the students table and display them in a tabular format.

Hints:

 Use cursor.execute with SELECT *.


 Loop through the result using cursor.fetchall.

def fetch_all_students(connection):
cursor = connection.cursor()
cursor.execute("SELECT * FROM students")
records = cursor.fetchall()
print("ID | Name | Age | Grade")
print("-" * 30)
for row in records:
print(f"{row[0]:<3} | {row[1]:<10} | {row[2]:<3} | {row[3]:<5}")

4. Update a Record

Write a script to update the grade of a specific student by their id.

Hints:

 Use UPDATE students SET grade = %s WHERE id = %s.


 Commit the transaction.

def update_student_grade(connection, student_id, new_grade):


cursor = connection.cursor()
sql = "UPDATE students SET grade = %s WHERE id = %s"
cursor.execute(sql, (new_grade, student_id))
connection.commit()
print(f"Student with ID {student_id} updated to grade {new_grade}.")

5. Delete a Record

Write a script to delete a student record by their id.

Hints:

 Use DELETE FROM students WHERE id = %s.


 Commit the transaction.

def delete_student(connection, student_id):


cursor = connection.cursor()
sql = "DELETE FROM students WHERE id = %s"
cursor.execute(sql, (student_id,))
connection.commit()
print(f"Student with ID {student_id} deleted.")

6. Search Records

Write a script to search for students by name. The script should handle partial matches (e.g.,
searching "John" should return "John Doe").

Hints:

 Use SELECT * FROM students WHERE name LIKE %s.


 Pass %search_term% as a parameter.

def search_students_by_name(connection, search_term):


cursor = connection.cursor()
sql = "SELECT * FROM students WHERE name LIKE %s"
cursor.execute(sql, (f"%{search_term}%",))
results = cursor.fetchall()
print(f"Students matching '{search_term}':")
for row in results:
print(row)

7. Implement Pagination

Write a script to fetch and display records in a paginated manner (e.g., 2 records per page).

Hints:

 Use LIMIT and OFFSET in SQL queries.


def fetch_students_paginated(connection, limit, offset):
cursor = connection.cursor()
sql = "SELECT * FROM students LIMIT %s OFFSET %s"
cursor.execute(sql, (limit, offset))
results = cursor.fetchall()
for row in results:
print(row)

8. Count Total Records

Write a script to count the total number of records in the students table.

Hints:

 Use SELECT COUNT(*) FROM students.

def count_total_students(connection):
cursor = connection.cursor()
cursor.execute("SELECT COUNT(*) FROM students")
total = cursor.fetchone()[0]
print(f"Total students: {total}")

9. Backup Table Data

Write a script to export the students table data to a CSV file.

Hints:

 Use Python's csv module.


 Fetch data with SELECT *.

import csv

def backup_students_to_csv(connection, file_name):


cursor = connection.cursor()
cursor.execute("SELECT * FROM students")
records = cursor.fetchall()
with open(file_name, mode="w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["ID", "Name", "Age", "Grade"])
writer.writerows(records)
print(f"Backup completed: {file_name}")

10. Restore Table Data

Write a script to import data from a CSV file into the students table.
Hints:

 Use Python’s csv module to read the file.


 Use cursor.executemany to insert records.

def restore_students_from_csv(connection, file_name):


cursor = connection.cursor()
with open(file_name, mode="r") as file:
reader = csv.reader(file)
next(reader) # Skip header row
rows = [tuple(row[1:]) for row in reader]
sql = "INSERT INTO students (name, age, grade) VALUES (%s, %s, %s)"
cursor.executemany(sql, rows)
connection.commit()
print(f"Data restored from {file_name}.")

Challenge

Combine all the above functionalities into a menu-driven program where users can perform
CRUD operations and backups interactively.

Menu:
1. Insert Student
2. View All Students
3. Update Student Grade
4. Delete Student
5. Search by Name
6. View Paginated Results
7. Count Total Students
8. Backup to CSV
9. Restore from CSV
10. Exit

You might also like