0% found this document useful (0 votes)
25 views10 pages

DB - Lab 13 - Lab Tasks

Uploaded by

Muhammad Shahbaz
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)
25 views10 pages

DB - Lab 13 - Lab Tasks

Uploaded by

Muhammad Shahbaz
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/ 10

Database Systems Lab (CS-232 )

Database Systems – Lab 13


Namal University Mianwali
Department of Computer Science

Lab Instructor Ms. Asiya Batool Dated 12-06-2024


Student Name Student Roll No
Max Marks 20 Obtained Marks

Lab 13 – Lab Tasks


Note:

Create a database with the following schema:

students: Stores student details. (id, name, dob, semester)


courses: Stores course details. (id, name, description)
enrollments: Stores the relationship between students and courses. (student id, course id, enrollement
Task 1
date)
audit_log: Logs changes made to the database. ( id, operation, table_name, record_id, timestamp,
description)

(You can use either python or MySQL for database creation)

Query

Output

Create a procedure that updates the audit log whenever a record is inserted, updated, or deleted from
the database tables. The procedure should take the operation, table name, record ID, and timestamp,
Task 2
and description as inputs. The description can contain the error message if the operation is not
performed successfully.

Query

Output

Write a Python program that gets values from the user as long as the user wants to add records and
Task 3
insert student records into the students table. Also update the audit log accordingly.

Query

Output

Write a Python program that adds multiple courses based on multiple user inputs. Update the log
Task 4
accordingly.
1
Query
Database Systems – Lab 13

Task 1: Create a database with the following schema

The database creation can be done using MySQL commands.

sql
Copy code
CREATE DATABASE school;
USE school;

CREATE TABLE students (


id INT PRIMARY KEY,
name VARCHAR(100),
dob DATE,
semester INT
);

CREATE TABLE courses (


id INT PRIMARY KEY,
name VARCHAR(100),
description TEXT
);

CREATE TABLE enrollments (


student_id INT,
course_id INT,
enrollment_date DATE,
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES students(id),
FOREIGN KEY (course_id) REFERENCES courses(id)
);

CREATE TABLE audit_log (


id INT PRIMARY KEY AUTO_INCREMENT,
operation VARCHAR(50),
table_name VARCHAR(50),
record_id INT,
timestamp DATETIME,
description TEXT
);

Task 2: Create a procedure that updates the audit log


sql
Copy code
DELIMITER //
CREATE PROCEDURE update_audit_log(
IN op VARCHAR(50),
IN tbl_name VARCHAR(50),
IN rec_id INT,

2
Database Systems – Lab 13

IN desc_text TEXT
)
BEGIN
INSERT INTO audit_log (operation, table_name, record_id, timestamp, description)
VALUES (op, tbl_name, rec_id, NOW(), desc_text);
END //
DELIMITER ;

Task 3: Python program to insert student records and update the audit log
python
Copy code
import mysql.connector as c
from mysql.connector import Error

def insert_student():
try:
dataBase = c.connect(
host="localhost",
user="root",
password="Namal.123",
database="school"
)

if dataBase.is_connected():
cursor = dataBase.cursor()

while True:
student_id = int(input("Enter Student ID: "))
student_name = input("Enter Student Name: ")
student_dob = input("Enter Student DOB (YYYY-MM-DD): ")
student_semester = int(input("Enter Student Semester: "))

query = "INSERT INTO students (id, name, dob, semester) VALUES (%s,
%s, %s, %s)"
cursor.execute(query, (student_id, student_name, student_dob,
student_semester))

# Update audit log


cursor.callproc('update_audit_log', ('INSERT', 'students',
student_id, 'Student record inserted.'))

dataBase.commit()
print("Student record inserted successfully.")

cont = input("Do you want to insert another record? (yes/no): ")


if cont.lower() != 'yes':
break

except Error as e:
print(f"Error occurred: {e}")
if dataBase.is_connected():
dataBase.rollback()

finally:
if dataBase.is_connected():

3
Database Systems – Lab 13

cursor.close()
dataBase.close()
print("MySQL connection is closed")

insert_student()

Task 4: Python program to add multiple courses


python
Copy code
def insert_courses():
try:
dataBase = c.connect(
host="localhost",
user="root",
password="Namal.123",
database="school"
)

if dataBase.is_connected():
cursor = dataBase.cursor()

while True:
course_id = int(input("Enter Course ID: "))
course_name = input("Enter Course Name: ")
course_description = input("Enter Course Description: ")

query = "INSERT INTO courses (id, name, description) VALUES (%s, %s,
%s)"
cursor.execute(query, (course_id, course_name, course_description))

# Update audit log


cursor.callproc('update_audit_log', ('INSERT', 'courses', course_id,
'Course record inserted.'))

dataBase.commit()
print("Course record inserted successfully.")

cont = input("Do you want to insert another course? (yes/no): ")


if cont.lower() != 'yes':
break

except Error as e:
print(f"Error occurred: {e}")
if dataBase.is_connected():
dataBase.rollback()

finally:
if dataBase.is_connected():
cursor.close()
dataBase.close()
print("MySQL connection is closed")

insert_courses()

4
Database Systems – Lab 13

Task 5: Python program to enroll a student in a course


python
Copy code
def enroll_student():
try:
dataBase = c.connect(
host="localhost",
user="root",
password="Namal.123",
database="school"
)

if dataBase.is_connected():
cursor = dataBase.cursor()

student_id = int(input("Enter Student ID: "))


course_id = int(input("Enter Course ID: "))
enrollment_date = input("Enter Enrollment Date (YYYY-MM-DD): ")

query = "INSERT INTO enrollments (student_id, course_id,


enrollment_date) VALUES (%s, %s, %s)"
cursor.execute(query, (student_id, course_id, enrollment_date))

# Update audit log


cursor.callproc('update_audit_log', ('INSERT', 'enrollments',
student_id, f'Student enrolled in course {course_id}.'))

dataBase.commit()
print("Student enrolled successfully.")

except Error as e:
print(f"Error occurred: {e}")
if dataBase.is_connected():
dataBase.rollback()

finally:
if dataBase.is_connected():
cursor.close()
dataBase.close()
print("MySQL connection is closed")

enroll_student()

Task 6: Create a procedure for enrollment and update log


sql
Copy code
DELIMITER //
CREATE PROCEDURE enroll_student_procedure(
IN s_id INT,
IN c_id INT,
IN enroll_date DATE
)
BEGIN

5
Database Systems – Lab 13

INSERT INTO enrollments (student_id, course_id, enrollment_date) VALUES (s_id,


c_id, enroll_date);
CALL update_audit_log('INSERT', 'enrollments', s_id, CONCAT('Student enrolled in
course ', c_id, '.'));
END //
DELIMITER ;

Task 7: Python program to update the semester of students enrolled in a specific course
python
Copy code
def update_student_semester():
try:
dataBase = c.connect(
host="localhost",
user="root",
password="Namal.123",
database="school"
)

if dataBase.is_connected():
cursor = dataBase.cursor()

course_id = int(input("Enter Course ID: "))


new_semester = int(input("Enter New Semester: "))

query = "UPDATE students SET semester = %s WHERE id IN (SELECT


student_id FROM enrollments WHERE course_id = %s)"
cursor.execute(query, (new_semester, course_id))

# Update audit log for each student


for student_id in cursor:
cursor.callproc('update_audit_log', ('UPDATE', 'students',
student_id[0], f'Student semester updated to {new_semester}.'))

dataBase.commit()
print("Student semesters updated successfully.")

except Error as e:
print(f"Error occurred: {e}")
if dataBase.is_connected():
dataBase.rollback()

finally:
if dataBase.is_connected():
cursor.close()
dataBase.close()
print("MySQL connection is closed")

update_student_semester()

Task 8: Python program to search for courses by name


python
Copy code

6
Database Systems – Lab 13

def search_courses():
try:
dataBase = c.connect(
host="localhost",
user="root",
password="Namal.123",
database="school"
)

if dataBase.is_connected():
cursor = dataBase.cursor()

course_name = input("Enter partial or full course name: ")

query = "SELECT * FROM courses WHERE name LIKE %s"


cursor.execute(query, ('%' + course_name + '%',))

courses = cursor.fetchall()
for course in courses:
print(f"ID: {course[0]}, Name: {course[1]}, Description:
{course[2]}")

except Error as e:
print(f"Error occurred: {e}")

finally:
if dataBase.is_connected():
cursor.close()
dataBase.close()
print("MySQL connection is closed")

search_courses()

Task 9: Procedure to retrieve names of students and their courses, and a Python
program to call it
sql
Copy code
DELIMITER //
CREATE PROCEDURE get_student_courses()
BEGIN
SELECT s.name AS student_name, c.name AS course_name
FROM students s
JOIN enrollments e ON s.id = e.student_id
JOIN courses c ON e.course_id = c.id;
END //
DELIMITER ;

Python program to call the procedure:

python
Copy code
def get_student_courses():
try:
dataBase = c.connect(

7
Database Systems – Lab 13

host="localhost",
user="root",
password="Namal.123",
database="school"
)

if dataBase.is_connected():
cursor = dataBase.cursor()

cursor.callproc('get_student_courses')

for result in cursor.stored_results():


rows = result.fetchall()
for row in rows:
print(f"Student Name: {row[0]}, Course Name: {row[1]}")

except Error as e:
print(f"Error occurred: {e}")

finally:
if dataBase.is_connected():
cursor.close()
dataBase.close()
print("MySQL connection is closed")

get_student_courses()

Task 10: Python program to group students by semester


python
Copy code
def group_students_by_semester():
try:
dataBase = c.connect(
host="localhost",
user="root
4o
Develop a Python program that groups student records by their semester and computes the total number
of students in each semester. The program should then display the student details for each semester,
including their names, IDs other relevant information."
ChatGPT

To develop a Python program that groups student records by their semester, computes the total number
of students in each semester, and displays the student details for each semester, you can use the
following approach. This program will use MySQL to retrieve and process the data.

Steps to Achieve the Task

1. Connect to the MySQL Database: Establish a connection to the MySQL database using
mysql.connector.
2. Retrieve Data: Use SQL queries to fetch the necessary data from the database.

8
Database Systems – Lab 13

3. Group Data by Semester: Process the data to group students by their semester and count the
number of students in each semester.
4. Display Data: Format and display the grouped data.

Python Code Implementation


python
Copy code
import mysql.connector as c
from mysql.connector import Error

def group_students_by_semester():
try:
# Establish connection to the database
dataBase = c.connect(
host="localhost",
user="root",
password="Namal.123",
database="school"
)

if dataBase.is_connected():
cursor = dataBase.cursor()

# SQL query to get student details grouped by semester


query = """
SELECT semester, id, name, dob
FROM students
ORDER BY semester, id
"""
cursor.execute(query)

# Fetch all rows from the query result


rows = cursor.fetchall()

# Dictionary to store students grouped by semester


semester_groups = {}

# Process each row


for row in rows:
semester = row[0]
student_details = {
'id': row[1],
'name': row[2],
'dob': row[3]
}
if semester not in semester_groups:
semester_groups[semester] = []
semester_groups[semester].append(student_details)

# Display the results


for semester, students in semester_groups.items():
print(f"\nSemester {semester}:")
print(f"Total Students: {len(students)}")
for student in students:

9
Database Systems – Lab 13

print(f"ID: {student['id']}, Name: {student['name']}, DOB:


{student['dob']}")

except Error as e:
print(f"Error occurred: {e}")

finally:
if dataBase.is_connected():
cursor.close()
dataBase.close()
print("MySQL connection is closed")

# Call the function to execute


group_students_by_semester()

10

You might also like