0% found this document useful (0 votes)
6 views

Computer Science Practical file

Uploaded by

bhattsumit504
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Computer Science Practical file

Uploaded by

bhattsumit504
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

COMPUTER SCIENCE

PRACTICAL FILE
Submitted by: Sumit Bhatt (XII- A)
INDEX
DATE AIM REMARKS

Python Functions-
24 April 2024 1. Write a function to check if a given number is prime

15 May 2024 2. Write a function to find GCD and LCM of two


numbers

22 May 2024 3. Write a program to find the greatest number in each


list of numbers using a function

29 May 2024 4. Write a function to check if a string contains all


alphabets (pangram)

07 August 2024 5. Write a function to find all prime factors of a number

14 August 2024 6.Write a program to read employee data from a text file
and print employees with salary > 5000.

21 August 2024 7. Write a program to read words from a text file and

create two separate files - one with words starting with 'a' and another

with remaining words.

28 August 2024 8. Write a program to find and replace specific words in a


text file

04 September 9. Write a program to maintain a phone directory


2024 (name, phone, email) with search and modify options

11 September 10. Write a program to store movie details and display


2024 movies by genre/year

18 September 11. Write a program to modify marks of a specific


2024 student in a binary file containing student records.

25 September 12. Write a program to read all content of "student.csv" and display
2024 records of only those students who scored more than 80 marks.
Records stored in students is in
format: Roll no., Name

16 October 13. Write a program to store student records in a CSV file


2024 and display students having marks above a given threshold

23 October 14. Create a password generator with options for


2024 length and character types (numbers)

30 October 15. Write a program to implement multiple stacks in a


2024 single array
DATE AIM REMARKS
06 November 16. Write a program to sort a stack using only push and pop
2024 operations

SQL queries (using one/two tables)


-- Consider tables 'HOSPITAL' (DoctorID, Name,

Specialization) and 'PATIENTS' (PatientID, Name, DoctorID,

Disease, AdmitDate)

13 November
1. Write SQL queries to:
2024

- Find doctors with more than 10 patients

- List patients by disease category

- Calculate average patients per specialization

- Find longest admitted patient

- Display doctor's current patient count

-- Consider tables 'RESTAURANT' (ItemID, Name,

Category, Price) and 'ORDERS' (OrderID, TableNo, ItemID,

Quantity, Date)

20 November
2. Write SQL queries to:
2024

- Find most ordered items

- Calculate daily revenue by category

- List tables with orders above average

- Display peak hours based on orders

- Find items never ordered

-- Consider tables 'SPORTS_CLUB' (MemberID,

Name, JoinDate, Plan) and 'ACTIVITIES' (ActivityID, MemberID,

Sport, Hours)

27 November
3. Write SQL queries to:
2024

- List members by activity hours

- Find most popular sport

- Calculate membership duration

- Display activity trends

- Find inactive members


DATE AIM REMARKS
-- Consider tables 'E_COMMERCE' (ProductID, Name, Stock) and
'REVIEWS' (ReviewID, ProductID,
Rating, Comment)

04 December
4. Write SQL queries to:
2024

- Find products with best reviews

- Calculate average rating by category

- List products with no reviews

- Display monthly review trends

- Find most reviewed products

-- Consider tables 'LIBRARY_MEMBERS' (MemberID,

Name, Type) and 'TRANSACTIONS' (TransID, BookID,

MemberID, IssueDate, ReturnDate)

04 December
5. Write SQL queries to:
2024

- Find members with overdue books

- Calculate fine for late returns

- Display popular books by member type

- List members with no transactions

- Find average book keeping duration

PYTHON-SQL CONNECTIVITY
11 December 1. Write a program to create a hospital management
2024 System

18 December 2. Write a program to implement an e-commerce order


2024 processing system

15 January 3. Write a program to create a sports club


2024 membership management system

15 January 4. Write a program to implement a library fine


2024 Calculation system
PRACTICAL-1

AIM: Write a function to check if a given number is prime


INPUT:
def is_prime(number):
if number < 2:
return ("Not a prime number")
for i in range(2, number):
if number % i == 0:
return ("Not a prime number")
return ("Prime number")
num = int(input("Enter the number: "))
print(is_prime(num))

OUTPUT:
PRACTICAL-2

AIM: Write a function to find GCD and LCM of two numbers


INPUT:
def find_gcd_lcm(a, b):
def gcd(x, y):
while y:
x, y = y, x % y
return x
def lcm(x, y):
return abs(x * y) // gcd(x, y)
return gcd(a, b), lcm(a, b)
print(f"GCD and LCM of 12,18: {find_gcd_lcm(12,
18)}")

OUTPUT:
PRACTICAL-3

AIM: Write a program to find the greatest number in each list of numbers
using a function.

INPUT:
def find_greatest(numbers):
greatest = numbers[0]
for num in numbers:
if num > greatest:
greatest = num
return greatest
list = eval(input("Enter the list: "))
print(f"Greatest in {list} is:", find_greatest(list))

OUTPUT:
PRACTICAL-4

AIM: Write a function to check if a string contains all alphabets (pangram).


INPUT:
def is_pangram(text):
alphabet = set('abcdefghijklmnopqrstuvwxyz')
return set(text.lower()) >= alphabet

# Test
if name == " main ":
test_string = "The quick brown fox jumps over the lazy
dog"
print(f"Is pangram? {is_pangram(test_string)}")

OUTPUT
PRACTICAL-5

AIM: Write a function to find all prime factors of a number


INPUT:
def prime_factors(n):
factors = []
d=2
while n > 1:
while n % d == 0:
factors.append(d)
n //= d
d += 1
if d * d > n:
if n > 1:
factors.append(n)
break
return factors

OUTPUT:
PRACTICAL-6

AIM: Write a program to read employee data from a text file and print
employees with salary > 5000.

INPUT:
print("Filtered Employe Records (Salary > 5000):")
f = open("employees.txt", 'r')
for line in f:
name, position, salary = line.strip().split(", ")
if int(salary) > 5000:
print(f"Name: {name}, Position: {position}, Salary:
{salary}")
f.close()

OUTPUT:
PRACTICAL-7

AIM: Write a program to read words from a text file and create two separate
files - one with words starting with 'a' and another with remaining words.
INPUT:

infile = open('existing_file.txt', 'r')


a = []
na = []
for line in infile:
word = line.strip()
if word[0].lower() == 'a':
a.append(word)
else:
na.append(word)
infile.close()

OUTPUT
PRACTICAL-8
AIM: Write a program to find and replace specific words in a text file
INPUT:
filename="text_handling/story.txt"
old_word=input("Word to replace: ")
new_word=input("Replace with: ")
file=open(filename,'r')
content=file.read()
file.close()
print("\nOriginal content:")
print(content)
new_content=""
i=0
while i<len(content):
if content[i:i+len(old_word)]==old_word:
new_content+=new_word
i+=len(old_word)
else:
new_content+=content[i]
i+=1
file=open(filename,'w')
file.write(new_content)
file.close()
print(f"\nReplaced all occurrences of '{old_word}' with
'{new_word}'")
print("\nNew content:")
print(new_content)

OUTPUT:
PRACTICAL-9
AIM: Write a program to store names and surnames in a binary file and display
records where name/surname starts with 'a.’
INPUT:

import pickle
file = open('usernames.dat', 'rb')
loaded_usernames = pickle.load(file)
filtered_usernames = []
for username in loaded_usernames:
if username.startswith('a'):
filtered_usernames.append(username)
if filtered_usernames:
print("All usernames:", loaded_usernames)
print("\nUsernames starting with 'a':", filtered_usernames)
else:
print("No usernames start with 'a'.")
file.close()

OUTPUT:
PRACTICAL-10
AIM: Write a program to store movie details and display movies by genre/year
INPUT:
import pickle
from typing import Dict, List, Optional
from datetime import datetime
class Movie:
def init (self, title: str, year: int, genre: str, director: str, rating:
float):
self.title = title
self.year = year
self.genre = genre
self.director = director
self.rating = rating
class MovieDatabase:
def init (self, filename: str):
self.filename = filename
self.movies: List[Movie] = []
self.load_database()
def load_database(self):
try:
with open(self.filename, 'rb') as f:
self.movies = pickle.load(f)
except (FileNotFoundError, EOFError):
self.movies = []
def save_database(self):
with open(self.filename, 'wb') as f:
pickle.dump(self.movies, f)
def add_movie(self, title: str, year: int, genre: str, director: str,
rating: float) -> bool:
movie = Movie(title, year, genre, director, rating)
self.movies.append(movie)
self.save_database()
return True
def get_movies_by_genre(self, genre: str) -> List[Movie]:
return [movie for movie in self.movies if movie.genre.lower()
== genre.lower()]
def get_movies_by_year(self, year: int) -> List[Movie]:
return [movie for movie in self.movies if movie.year == year] def
display_movies(self, movies: List[Movie]):
if not movies:
print("No movies found!")
return
print("\n" + "="*50)
for movie in movies:
print(f"Title: {movie.title}") print(f"Year:
{movie.year}")
print(f"Genre: {movie.genre}")
print(f"Director: {movie.director}")
print(f"Rating: {movie.rating}/10") print("-
"*50)

OUTPUT:
PRACTICAL-11
AIM: Write a program to modify marks of a specific student in a binary file
containing student records.

INPUT:
import pickle
with open("binary_handling/student.dat","ab") as f:
rollno=int(input("Enter Roll Number: "))
name=input("Enter Name: ")
marks=int(input("Enter Marks: "))
rec=[rollno,name,marks]
pickle.dump(rec,f)

OUTPUT
PRACTICAL-12

AIM: Write a program to read all content of "student.csv" and display


records of only those students who scored more than 80 marks. Records stored
in students is in format: Rollno, Name,

import csv
f = open("student.csv", "r")
d = csv.reader(f)
next(f)
print("Students Scored More than 80")
print()
for i in d:
if int(i[2]) > 80:
print("Roll Number =", i[0])
print("Name =", i[1])
print("Marks =", i[2])
print("-")
f.close()

OUTPUT:
PRACTICAL-13
AIM: Write a program to store student records in a CSV file and display students
having marks above a given threshold

import csv
def create_student_records():
with open('students.csv', 'w', newline='') as file: writer =
csv.writer(file)
writer.writerow(['Roll', 'Name', 'Marks'])

n = int(input("Enter number of students: "))


for i in range(n):
roll = input(f"Enter roll number {i+1}: ") name =
input(f"Enter name {i+1}: ")
marks = float(input(f"Enter marks {i+1}: ")) writer.writerow([roll, name, marks])

def find_students_above_threshold():
threshold = float(input("\nEnter marks threshold: ")) print(f"\nStudents with marks above
{threshold}:")

with open('students.csv', 'r') as file: reader =


csv.DictReader(file)
for row in reader:
if float(row['Marks']) > threshold:
print(f"Name: {row['Name']}, Marks: {row['Marks']}")

create_student_records()
find_students_above_threshold()
OUTPUT:
PRACTICAL-14
AIM: Create a password generator with options for length and character
types (numbers)
import random
def create_password(length):
numbers='0123456789'
password=''
for i in range(length): password+=random.choice(numbers)
return password
print("Simple Password Generator") print("-
"*25)
length=int(input("Password length: "))
print("\nHere are 5 password options:") print("-
"*25)
for i in range(5):
password=create_password(length) print(f"Option
{i+1}: {password}")

OUTPUT
PRACTICAL-15
AIM: Write a program to implement multiple stacks in a single array

def stack_operations():
stack = []
while True:
print("\nStack Operations:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
item = input("Enter item to push: ")
stack.append(item)
print(f"{item} pushed to stack")
elif choice == '2':
if stack:
print(f"{stack.pop()} popped from stack")
else:
print("Stack is empty")
elif choice == '3':
if stack:
print(f"Top element is: {stack[-1]}")
else:
print("Stack is empty")
elif choice == '4':
if stack:
print("\nStack elements from top:")
for item in reversed(stack):
print(f"| {item} |")
print("-" * 20)
else:
print("Stack is empty")
elif choice == '5':
print("Exiting program...")
break
else:
print("Invalid choice! Please try again")
if name == " main ":
stack_operations()

OUTPUT:
PRACTICAL-16
AIM: Write a program to sort a stack using only push and pop operations
def sort_stack(stack):
temp_stack = []
while stack:
temp = stack.pop()
while temp_stack and temp_stack[-1] > temp:
stack.append(temp_stack.pop())
temp_stack.append(temp)
while temp_stack:
stack.append(temp_stack.pop())
return stack
if name == " main ":
test_stack = []
test_data = [5, 2, 9, 1, 7, 6, 3]
print("Original stack:")
for item in test_data:
test_stack.append(item)
print(item, end=" ")
print()
sorted_stack = sort_stack(test_stack)
print("\nSorted stack:")
for item in sorted_stack:
print(item, end=" ")
print()

OUTPUT:
PRACTICAL-17
AIM: Write SQL queries : HOSPITAL
Table

CREATE TABLE HOSPITAL ( DoctorID INT PRIMARY KEY, Name VARCHAR(100),


Specialization VARCHAR(50))
INSERT INTO HOSPITAL VALUES(doctor_id,doctor_name,specialization)
(1, 'Dr. Smith', 'Cardiology'),
(2, 'Dr. Johnson', 'Paediatrics'),
(3, 'Dr. Williams', 'Neurology'),
(4, 'Dr. Brown', 'Orthopaedics'),
(5, 'Dr. Davis', 'General Medicine');

PATIENT Table
CREATE TABLE PATIENTS (PatientID INT PRIMARY KEY, Name VARCHAR(100),
DoctorID INT, Disease VARCHAR(100), AdmitDate DATE, FOREIGN KEY
(DoctorID) REFERENCES HOSPITAL(DoctorID));
INSERT INTO PATIENTS VALUES(PatientID,Name,DoctorID,Disease,AdmitDate)
(1, 'John Doe', 1, 'Heart Disease', '2024-01-15'),
(2, 'Jane Smith', 2, 'Flu', '2024-02-01'),
(3, 'Bob Wilson', 1, 'Hypertension', '2024-01-20'),
(4, 'Alice Brown', 3, 'Migraine', '2024-02-10'),
(5, 'Charlie Davis', 4, 'Fracture', '2024-02-15');
1. Find doctors with more than 10 patients
SELECT h.Name, COUNT(p.PatientID) as PatientCount FROM HOSPITAL h LEFT JOIN
PATIENTS p ON h.DoctorID = p.DoctorID GROUP BY h.DoctorID, h.Name HAVING
COUNT(p.PatientID) > 10;

2. List patients by disease category


SELECT Disease, COUNT(*) as PatientCount FROM PATIENTS GROUP BY Disease
ORDER BY PatientCount DESC;

3. Calculate average patients per specialization


SELECT h.Specialization, AVG(PatientCount) as AvgPatients FROM (SELECT DoctorID,
COUNT(*) as PatientCount FROM PATIENTS GROUP BY DoctorID) p JOIN HOSPITAL h
ON h.DoctorID = p.DoctorID GROUP BY h.Specialization;

4. Find longest admitted patient


SELECT p.Name, p.AdmitDate, DATEDIFF(CURRENT_DATE, p.AdmitDate) as
DaysAdmitted FROM PATIENTS p ORDER BY DaysAdmitted DESC;

5. Display doctor's current patient count


SELECT h.Name, COUNT(p.PatientID) as CurrentPatients FROM HOSPITAL h LEFT JOIN
PATIENTS p ON h.DoctorID = p.DoctorID GROUP BY h.DoctorID, h.Name ORDER BY
CurrentPatients DESC;
OUTPUT:
PRACTICAL-18

RESTURANT Table
CREATE TABLE RESTAURANT (ItemID INT PRIMARY KEY, Name VARCHAR(100) NOT
NULL, Category VARCHAR(50) NOT NULL, Price DECIMAL(10,2) NOT NULL);
INSERT INTO RESTAURANT VALUES
(1, 'Margherita Pizza', 'Pizza', 12.99),
(2, 'Chicken Alfredo', 'Pasta', 15.99),
(3, 'Caesar Salad', 'Salad', 8.99),
(4, 'Chocolate Cake', 'Dessert', 6.99),
(5, 'Espresso', 'Beverages', 3.99),
(6, 'Garlic Bread', 'Appetizer', 4.99);

ORDER Table
CREATE TABLE ORDERS (OrderID INT PRIMARY KEY, TableNo INT NOT NULL, ItemID
INT, Quantity INT NOT NULL, Date DATETIME NOT NULL, FOREIGN KEY (ItemID)
REFERENCES RESTAURANT(ItemID));
INSERT INTO ORDERS VALUES
(1, 1, 1, 2, '2024-03-15 18:30:00'),
(2, 2, 2, 1, '2024-03-15 19:00:00'),
(3, 1, 3, 1, '2024-03-15 18:35:00'),
(4, 3, 1, 1, '2024-03-15 20:00:00'),
(5, 2, 4, 2, '2024-03-15 19:30:00'),
(6, 4, 2, 2, '2024-03-15 20:30:00');
1. Find most ordered items
SELECT
r.Name,
COUNT(*) as OrderCount,
SUM(o.Quantity) as TotalQuantity
FROM RESTAURANT r
JOIN ORDERS o ON r.ItemID = o.ItemID
GROUP BY r.ItemID, r.Name
ORDER BY TotalQuantity DESC;

2. Calculate daily revenue by category


SELECT
r.Category,
DATE(o.Date) as OrderDate,
SUM(r.Price * o.Quantity) as Revenue
FROM RESTAURANT r
JOIN ORDERS o ON r.ItemID = o.ItemID
GROUP BY r.Category, DATE(o.Date)
ORDER BY OrderDate, Revenue DESC;

3. List tables with orders above average


WITH TableOrders AS (SELECT TableNo, COUNT(*) as OrderCount, SUM(Quantity) as
TotalItems FROM ORDERS GROUP BY TableNo)
SELECT TableNo, OrderCount, TotalItems FROM TableOrders WHERE TotalItems >
(SELECT AVG(TotalItems) FROM TableOrders);

4. Display peak hours based on orders


SELECT
HOUR(Date) as HourOfDay,
COUNT(*) as OrderCount
FROM ORDERS
GROUP BY HOUR(Date)
ORDER BY OrderCount DESC;
5. Find items never ordered
SELECT
r.ItemID,
r.Name,
r.Category,
r.Price
FROM RESTAURANT r
LEFT JOIN ORDERS o ON r.ItemID = o.ItemID
WHERE o.OrderID IS NULL;

OUTPUT:
PRACTICAL-19
SPORTS_CLUB Table
CREATE TABLE SPORTS_CLUB (MemberID INT PRIMARY KEY, Name
VARCHAR(100) NOT NULL, JoinDate DATE NOT NULL, Plan
VARCHAR(50) NOT NULL);
INSERT INTO SPORTS_CLUB VALUES(MemberID, Name, JoinDate, Plan)
(1, 'John Smith', '2023-01-15', 'Premium'),
(2, 'Sarah Johnson', '2023-03-20', 'Basic'),
(3, 'Mike Wilson', '2023-02-10', 'Premium'),
(4, 'Emma Davis', '2023-04-05', 'Basic'),
(5, 'Tom Brown', '2023-01-01', 'Premium'),
(6, 'Lisa Anderson', '2023-05-15', 'Basic');

ACTIVITIES Table
CREATE TABLE ACTIVITIES (ActivityID INT PRIMARY KEY, MemberID INT,
Sport VARCHAR(50) NOT NULL, Hours DECIMAL(5,2) NOT NULL,
ActivityDate DATE NOT NULL, FOREIGN KEY (MemberID) REFERENCES
SPORTS_CLUB(MemberID));
INSERT INTO ACTIVITIES VALUES(ActivityID, MemberID, Sport,
Hours,ActivityDate)
(1, 1, 'Tennis', 2.0, '2024-03-15'),
(2, 1, 'Swimming', 1.5, '2024-03-16'),
(3, 2, 'Yoga', 1.0, '2024-03-15'),
(4, 3, 'Tennis', 1.5, '2024-03-15'),
(5, 4, 'Swimming', 1.0, '2024-03-16'),
(6, 5, 'Tennis', 2.0, '2024-03-16');
1. List members by activity hours
SELECT sc.Name, SUM(a.Hours) as TotalHours, COUNT(DISTINCT a.Sport) as
DifferentSports FROM SPORTS_CLUB sc LEFT JOIN ACTIVITIES a ON
sc.MemberID = a.MemberID GROUP BY sc.MemberID, sc.Name ORDER BY
TotalHours DESC;

2. Find most popular sport


SELECT Sport, COUNT(DISTINCT MemberID) as UniqueMembers,
SUM(Hours) as TotalHours FROM ACTIVITIES GROUP BY Sport ORDER BY
UniqueMembers DESC, TotalHours DESC;

3. Calculate membership duration


SELECT Name, JoinDate, DATEDIFF(CURRENT_DATE, JoinDate) as
DaysSinceJoining, Plan FROM SPORTS_CLUB ORDER BY DaysSinceJoining
DESC;

4. Display activity trends


SELECT DATE(ActivityDate) as Date, Sport, COUNT(DISTINCT MemberID) as
MemberCount, SUM(Hours) as TotalHours FROM ACTIVITIES GROUP BY
DATE(ActivityDate), Sport ORDER BY Date, TotalHours DESC;

5. Find inactive members (no activities in last 30 days)


SELECT sc.MemberID, sc.Name, sc.Plan, MAX(a.ActivityDate) as
LastActivityDate FROM SPORTS_CLUB sc LEFT JOIN ACTIVITIES a ON
sc.MemberID = a.MemberID GROUP BY sc.MemberID, sc.Name, sc.Plan
HAVING LastActivityDate IS NULL OR LastActivityDate <
DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) ORDER BY LastActivityDate;
OUTPUT:
PRACTICAL-20
E_COMMERCE Table
CREATE TABLE E_COMMERCE (ProductID INT PRIMARY KEY, Name VARCHAR(100) NOT
NULL, Category VARCHAR(50) NOT NULL, Stock INT NOT NULL, Price DECIMAL(10,2)
NOT NULL);
INSERT INTO E_COMMERCE VALUES
(1, 'Smartphone X', 'Electronics', 50, 699.99),
(2, 'Running Shoes', 'Sports', 100, 89.99),
(3, 'Coffee Maker', 'Appliances', 30, 129.99),
(4, 'Laptop Pro', 'Electronics', 25, 1299.99),
(5, 'Fitness Tracker', 'Electronics', 75, 79.99),
(6, 'Gaming Console', 'Electronics', 20, 499.99);

REVIEWS Table
CREATE TABLE REVIEWS (ReviewID INT PRIMARY KEY, ProductID INT, Rating INT CHECK
(Rating BETWEEN 1 AND 5), Comment TEXT, ReviewDate DATE NOT NULL, FOREIGN KEY
(ProductID) REFERENCES E_COMMERCE(ProductID));
INSERT INTO REVIEWS VALUES
(1, 1, 5, 'Great phone!', '2024-03-01'),
(2, 1, 4, 'Good but expensive', '2024-03-02'),
(3, 2, 5, 'Very comfortable', '2024-03-03'),
(4, 3, 3, 'Average product', '2024-03-04'),
(5, 4, 5, 'Excellent laptop', '2024-03-05'),
(6, 1, 4, 'Nice features', '2024-03-06');
1. Find products with best reviews
SELECT e.Name, COUNT(r.ReviewID) as ReviewCount, AVG(r.Rating) as AvgRating,
MIN(r.Rating) as MinRating, MAX(r.Rating) as MaxRating FROM E_COMMERCE e LEFT
JOIN REVIEWS r ON e.ProductID = r.ProductID GROUP BY e.ProductID, e.Name HAVING
ReviewCount > 0 ORDER BY AvgRating DESC, ReviewCount DESC;

2. Calculate average rating by category


SELECT e.Category, COUNT(DISTINCT e.ProductID) as ProductCount, COUNT(r.ReviewID)
as TotalReviews, AVG(r.Rating) as AvgRating FROM E_COMMERCE e LEFT JOIN REVIEWS r
ON e.ProductID = r.ProductID GROUP BY e.Category ORDER BY AvgRating DESC;

3. List products with no reviews


SELECT ProductID, Name, Category, Stock, Price FROM E_COMMERCE e WHERE NOT
EXISTS (SELECT 1 FROM REVIEWS r WHERE r.ProductID = e.ProductID);

4. Display monthly review trends


SELECT DATE_FORMAT(ReviewDate, '%Y-%m') as Month, COUNT(*) as ReviewCount,
AVG(Rating) as AvgRating FROM REVIEWS GROUP BY DATE_FORMAT(ReviewDate, '%Y-
%m') ORDER BY Month DESC;

5. Find most reviewed products


SELECT e.Name, COUNT(r.ReviewID) as ReviewCount, e.Category, e.Price FROM
E_COMMERCE e JOIN REVIEWS r ON e.ProductID = r.ProductID GROUP BY e.ProductID,
e.Name, e.Category, e.Price ORDER BY ReviewCount DESC;
OUTPUT:
PRACTICAL-21
LIBRARY_MEMEBERS Table
CREATE TABLE LIBRARY_MEMBERS (MemberID INT PRIMARY KEY, Name VARCHAR(100)
NOT NULL, Type VARCHAR(50) NOT NULL, JoinDate DATE NOT NULL);
INSERT INTO LIBRARY_MEMBERS VALUES
(1, 'John Smith', 'Student', '2023-09-01'),
(2, 'Mary Johnson', 'Faculty', '2023-08-15'),
(3, 'David Wilson', 'Regular', '2023-10-01'),
(4, 'Sarah Brown', 'Student', '2023-09-15'),
(5, 'Michael Davis', 'Faculty', '2023-08-01');

BOOKS Table
CREATE TABLE BOOKS (BookID INT PRIMARY KEY, Title VARCHAR(200) NOT NULL,
Author VARCHAR(100) NOT NULL, Category VARCHAR(50) NOT NULL, Available
BOOLEAN DEFAULT TRUE);
INSERT INTO BOOKS VALUES
(1, 'Database Systems', 'Thomas Anderson', 'Technical', TRUE),
(2, 'Modern Physics', 'Robert Smith', 'Science', TRUE),
(3, 'World History', 'Emma Thompson', 'History', TRUE),
(4, 'Programming in Python', 'John Davis', 'Technical', TRUE),
(5, 'Organic Chemistry', 'Lisa Wilson', 'Science', TRUE)

TRANSACTIONS Table
CREATE TABLE TRANSACTIONS (TransID INT PRIMARY KEY, BookID INT, MemberID INT,
IssueDate DATE NOT NULL, ReturnDate DATE, DueDate DATE NOT NULL, FOREIGN KEY
(BookID) REFERENCES BOOKS(BookID), FOREIGN KEY (MemberID) REFERENCES
LIBRARY_MEMBERS(MemberID));
INSERT INTO TRANSACTIONS VALUES
(1, 1, 1, '2024-03-01', '2024-03-15', '2024-03-15'),
(2, 2, 2, '2024-03-05', NULL, '2024-03-19'),
(3, 3, 3, '2024-03-10', '2024-03-17', '2024-03-24'),
(4, 4, 1, '2024-03-15', NULL, '2024-03-29'),
(5, 5, 4, '2024-03-12', NULL, '2024-03-26');
1. Find members with overdue books
SELECT m.MemberID, m.Name, m.Type, b.Title, t.IssueDate, t.DueDate,
DATEDIFF(CURRENT_DATE, t.DueDate) as DaysOverdue FROM LIBRARY_MEMBERS m
JOIN TRANSACTIONS t ON m.MemberID = t.MemberID JOIN BOOKS b ON t.BookID =
b.BookID WHERE t.ReturnDate IS NULL AND t.DueDate < CURRENT_DATE ORDER BY
DaysOverdue DESC;

2. Calculate fine for late returns


SELECT m.Name, b.Title, t.IssueDate, t.ReturnDate, t.DueDate, CASE WHEN t.ReturnDate
IS NULL THEN GREATEST(DATEDIFF(CURRENT_DATE, t.DueDate), 0) * 2 ELSE
GREATEST(DATEDIFF(t.ReturnDate, t.DueDate), 0) * 2 END as Fine FROM TRANSACTIONS
t JOIN LIBRARY_MEMBERS m ON t.MemberID = m.MemberID JOIN BOOKS b ON t.BookID
= b.BookID WHERE (t.ReturnDate > t.DueDate) OR (t.ReturnDate IS NULL AND t.DueDate
< CURRENT_DATE);

3. Display popular books by member type


SELECT m.Type as MemberType, b.Category, COUNT(*) as BorrowCount,
COUNT(DISTINCT b.BookID) as UniqueBooks FROM TRANSACTIONS t JOIN
LIBRARY_MEMBERS m ON t.MemberID = m.MemberID JOIN BOOKS b ON t.BookID =
b.BookID GROUP BY m.Type, b.Category ORDER BY m.Type, BorrowCount DESC;

4. List members with no transactions


SELECT m.MemberID, m.Name, m.Type, m.JoinDate FROM LIBRARY_MEMBERS m LEFT
JOIN TRANSACTIONS t ON m.MemberID = t.MemberID WHERE t.TransID IS NULL;

5. Find average book keeping duration


SELECT b.Category, COUNT(*) as TotalBorrowings, AVG(CASE WHEN t.ReturnDate IS NULL
THEN DATEDIFF(CURRENT_DATE, t.IssueDate) ELSE DATEDIFF(t.ReturnDate, t.IssueDate)
END) as AvgDaysKept FROM TRANSACTIONS t JOIN BOOKS b ON t.BookID = b.BookID
GROUP BY b.Category ORDER BY AvgDaysKept DESC;
OUTPUT:
PRACTICAL-22
AIM: Sql Connectivity Queries
Write a program to connect to MySQL database and create a student table
import mysql.connector

def create_student_table():
conn = None
cursor = None
try:
# Establish connection
conn = mysql.connector.connect(host="localhost", user="root",password="@goth",
database="school")
cursor = conn.cursor()

# Create table query


create_table_query = """
CREATE TABLE IF NOT EXISTS students ( roll_no INT PRIMARY KEY,name VARCHAR(50) NOT
NULL,class VARCHAR(10) NOT NULL,marks FLOAT)
"""
cursor.execute(create_table_query)
conn.commit()
print("Table created successfully")

except mysql.connector.Error as e:
print(f"Error: {e}")

finally:
if cursor:
cursor.close()
if conn and conn.is_connected():
conn.close()
print("MySQL connection closed")

# Call the function


create_student_table()
OUTPUT:
PRACTICAL-23
Write a program to insert multiple student records with user input
import mysql.connector

def insert_student_records():
try:
conn = mysql.connector.connect(host="localhost", user="root", password="@goth",
database="school")
cursor = conn.cursor()

n = int(input("Enter number of students: "))


for i in range(n):
print(f"\nStudent {i+1} details:")
values = (
int(input("Roll No: ")),
input("Name: "),
input("Class: "),
float(input("Marks: "))
)
cursor.execute("""
INSERT INTO students (roll_no, name, class, marks)
VALUES (%s, %s, %s, %s)
""", values)

conn.commit()
print("\nRecords inserted successfully")

except mysql.connector.Error as e:
print(f"Database Error: {e}")
except ValueError as e:
print(f"Input Error: Please enter valid data")
finally:
if 'conn' in locals() and conn.is_connected():
cursor.close()
conn.close()
print("MySQL connection closed")

# Run the function


insert_student_records()
OUTPUT:
PRACTICAL-24
Write a program to display all records and implement name- based search
import mysql.connector

def display_and_search():
try:
conn = mysql.connector.connect(host="localhost", user="root", password="@goth",
database="school")
cursor = conn.cursor()

while True:
print("\n=== Student Record System ===")
print("1. Display all records")
print("2. Search by name")
print("3. Exit")
print("=" * 26)

choice = input("Enter your choice (1-3): ")

if choice == '1':
cursor.execute("SELECT * FROM students")
records = cursor.fetchall()
print("\nStudent Records:")
print("-" * 60)
print("Roll No | Name | Class | Marks")
print("-" * 60)
for record in records:
print(f"{record[0]:^8} | {record[1]:<12} | {record[2]:^7} | {record[3]:>6.2f}")
print("-" * 60)

elif choice == '2':


name = input("Enter name to search: ")
cursor.execute("SELECT * FROM students WHERE name LIKE %s", (f"%{name}%",))
records = cursor.fetchall()
if records:
print("\nMatching Records:")
print("-" * 60)
print("Roll No | Name | Class | Marks")
print("-" * 60)
for record in records:
print(f"{record[0]:^8} | {record[1]:<12} | {record[2]:^7} | {record[3]:>6.2f}")
print("-" * 60)
else:
print("\nNo matching records found")

elif choice == '3':


print("\nExiting program...")
break

else:
print("\nInvalid choice! Please enter 1, 2, or 3")

except mysql.connector.Error as e:
print(f"\nDatabase Error: {e}")
finally:
if 'conn' in locals() and conn.is_connected():
cursor.close()
conn.close()
print("\nDatabase connection closed")

# Run the function


display_and_search()

OUTPUT:
PRACTICAL-25
Write a program to update and delete student records based on roll number
import mysql.connector
2|
def update_delete_records():
try:
conn = mysql.connector.connect(host="localhost", user="root", password="@goth",
database="school")
cursor = conn.cursor()

while True:
print("\n=== Student Record Management ===\n1. Update student marks\n2. Delete
student record\n3. Exit\n" + "=" * 30)
choice = input("Enter your choice (1-3): ")

if choice == '1':
try:
roll_no, new_marks = int(input("Enter roll number to update: ")), float(input("Enter
new marks (0-100): "))
if 0 <= new_marks <= 100:
cursor.execute("UPDATE students SET marks = %s WHERE roll_no = %s",
(new_marks, roll_no))
conn.commit()
print("\nMarks updated successfully" if cursor.rowcount > 0 else "\nStudent not
found")
else: print("\nMarks must be between 0 and 100")
except ValueError: print("\nPlease enter valid numbers")

elif choice == '2':


try:
roll_no = int(input("Enter roll number to delete: "))
cursor.execute("SELECT name FROM students WHERE roll_no = %s", (roll_no,))
student = cursor.fetchone()
if student:
if input(f"\nAre you sure you want to delete record for student {student[0]}? (y/n):
").lower() == 'y':
cursor.execute("DELETE FROM students WHERE roll_no = %s", (roll_no,))
conn.commit()
print("\nRecord deleted successfully")
else: print("\nDeletion cancelled")
else: print("\nStudent not found")
except ValueError: print("\nPlease enter a valid roll number")

elif choice == '3': break


else: print("\nInvalid choice! Please enter 1, 2, or 3")

except mysql.connector.Error as e: print(f"\nDatabase Error: {e}")


finally:
if 'conn' in locals() and conn.is_connected():
cursor.close()
conn.close()
print("Database connection closed")

# Run the function


update_delete_records()

OUTPUT:

You might also like