0% found this document useful (0 votes)
18 views37 pages

PRACTICAL FILE (Final)

Uploaded by

rajeshraj070907
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views37 pages

PRACTICAL FILE (Final)

Uploaded by

rajeshraj070907
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

PRACTICAL FILE

COMPUTER SCIENCE

MADE BY:

NAME: Dhruv Verma


CLASS: XII A
ROLL No:
SESSION: 2024-25
INDEX

1.) PYTHON PROGRAMS

2.) MySQL COMMANDS


# Ques-1: Write a program to calculate the mean of a given list of numbers.

list=[]
s=0
n=int(input("Enter number of numbers to be entered:"))
for i in range(n):
a=int(input("Enter number:"))
list.append(a)
s=s+a
print("The mean of the entered list is=",s/n)

Enter number of numbers to be entered:5


Enter number:7
Enter number:3
Enter number:8
Enter number:20
Enter number:2
The mean of the entered list is= 8.0
# Ques-2: Write a program to calculate the minimum element of a given list of numbers.

list=[]
n=int(input("Enter number of numbers to be entered:"))
for i in range(n):
a=int(input("Enter number:"))
list.append(a)
x=min(list)
print("The minimum element of the entered list is=",x)

Enter number of numbers to be entered:5


Enter number:1
Enter number:2
Enter number:3
Enter number:0
Enter number:5
The minimum element of the entered list is= 0
# Ques-3: Write a code to calculate and display total marks and percentage of a student from a
# given list storing the marks of a student.

list=[]
a=int(input("Enter marks in English:"))
b=int(input("Enter marks in Maths:"))
c=int(input("Enter marks in Physics:"))
d=int(input("Enter marks in Chemistry:"))
e=int(input("Enter marks in Computer Science:"))
list.append([a,b,c,d,e])
print("Total Marks=",a+b+c+d+e)
print("Percentage=",((a+b+c+d+e)/500)*100)

Enter marks in English:94


Enter marks in Maths:95
Enter marks in Physics:95
Enter marks in Chemistry:94
Enter marks in Computer Science:96
Total Marks= 474
Percentage= 94.8
# Ques-4: Write a program to multiply an element by 2 if it is an odd index for a given list
# containing both numbers and strings.

list=[]
n=int(input("Enter length of list:"))
for i in range(n):
x=eval(input("Enter a string or a number to be entered:"))
if(i%2!=0):
a=x*2
list.append(a)
else:
list.append(x)
print("The list is=",list)

Enter length of list:6


Enter a string or a number to be entered:56
Enter a string or a number to be entered:210
Enter a string or a number to be entered:'abc'
Enter a string or a number to be entered:'dhruv'
Enter a string or a number to be entered:78
Enter a string or a number to be entered:32
The list is= [56, 420, 'abc', 'dhruvdhruv', 78, 64]
# Ques-5: Write a program to count the frequency of an element in a list.

list=[]
c=0
n=int(input("Enter length of list:"))
for i in range(n):
x=input("Enter element:")
list.append(x)
print("The list is=",list)
a=input("Choose an element from the above list:")
for j in list:
if(j==a):
c=c+1
print("The frequency of element'",a,"'in the entered list is=",c)

Enter length of list:6


Enter element:6
Enter element:2
Enter element:a
Enter element:j
Enter element:2
Enter element:2
The list is= ['6', '2', 'a', 'j', '2', '2']
Choose an element from the above list:2
The frequency of element' 2 'in the entered list is= 3
# Ques-6: Write a python program to shift elements of a list so that the first element moves to
# the second index and second index to the third index, and so on, and the last element shifts
# to the first position.
# Suppose the list is: [10,20,30,40]
# After shifting it should look like: [40,10,20,30]

list=[]
n=int(input("Enter the length of your list:"))
for i in range(n):
x=eval(input("Enter element:"))
list.append(x)
print("Your list is=",list)
if (len(list)>0):
last_element=list.pop()
list.insert(0,last_element)
print("After shifting the list is=",list)

Enter the length of your list:4


Enter element:10
Enter element:20
Enter element:30
Enter element:40
Your list is= [10, 20, 30, 40]
After shifting the list is= [40, 10, 20, 30]
# Ques-7: A list Num contains the following elements:
# 3,25,13,6,35,8,14,45
# Write a function to swap the content with the next value divisible by 5 so that the
# resultant list will look like:
# 25,3,13,35,6,8,45,14

list=[3,25,13,6,35,8,14,45]
i=0
while (i<len(list)-1):
if (list[i]%5!=0):
for j in range(i+1,len(list)):
if list[j]%5==0:
list[i],list[j]=list[j],list[i]
break
i=i+1
print("The modified list is=",list)

The modified list is= [25, 3, 13, 35, 6, 8, 45, 14]


# Ques-8: Write a program to accept values from a user in a tuple.
# Add a tuple to it and display its elements one by one.
# Also display its maximum and minimum value.

user_input=input("Enter values separated by spaces: ")


user_tuple=tuple(map(int, user_input.split()))
additional_tuple=(10, 20, 30, 40)
combined_tuple=user_tuple+additional_tuple
print("Combined tuple elements:")
for element in combined_tuple:
print(element)
print("Maximum value in the combined tuple:",max(combined_tuple))
print("Minimum value in the combined tuple:",min(combined_tuple))

Enter values separated by spaces: 1 23 45 23 1 33 78 6 56


Combined tuple elements:
1
23
45
23
1
33
78
6
56
10
20
30
40
Maximum value in the combined tuple: 78
Minimum value in the combined tuple: 1
# Ques-9: Write a program to input any values for two tuples. Print it, interchange it and then
# compare them.

tuple1_input=input("Enter values for the first tuple, separated by spaces:")


tuple1=tuple(map(int, tuple1_input.split()))
tuple2_input=input("Enter values for the second tuple, separated by spaces:")
tuple2 = tuple(map(int, tuple2_input.split()))
print("Original tuples:")
print("Tuple 1:",tuple1)
print("Tuple 2:",tuple2)
tuple1,tuple2=tuple2,tuple1
print("Interchanged tuples:")
print("Tuple 1:",tuple1)
print("Tuple 2:",tuple2)
if tuple1==tuple2:
print("The tuples are equal.")
else:
print("The tuples are not equal.")

Enter values for the first tuple, separated by spaces:1 2 3 4 5 6


Enter values for the second tuple, separated by spaces:4 5 6 7 8 9 1
Original tuples:
Tuple 1: (1, 2, 3, 4, 5, 6)
Tuple 2: (4, 5, 6, 7, 8, 9, 1)
Interchanged tuples:
Tuple 1: (4, 5, 6, 7, 8, 9, 1)
Tuple 2: (1, 2, 3, 4, 5, 6)
The tuples are not equal.
# Ques-10: Write a python program to input 'n' classes and names of their class teachers to
# store them in a dictionary and display the same.
# Also accept a particular class from the user and display the name of the class teacher of that
# class.

class_teachers={}
n=int(input("Enter the number of classes:"))
for i in range (n):
class_name=input("Enter the name of the class "+str(i+1)+" :")
teacher_name=input("Enter the name of the class teacher for "+class_name+" :")
class_teachers[class_name]=teacher_name
print("Classes and their class teachers:")
for class_name,teacher_name in class_teachers.items():
print("Class:",class_name,", Class Teacher's name:",teacher_name)
search_class=input("Enter the name of the class to find its class teacher:")
if search_class in class_teachers:
print("The Class Teacher of",search_class,"is",class_teachers[search_class],".")
else:
print("No information found for the class",search_class,".")

Enter the number of classes:4


Enter the name of the class 1 :A
Enter the name of the class teacher for A :Dhruv
Enter the name of the class 2 :B
Enter the name of the class teacher for B :Sarthak
Enter the name of the class 3 :C
Enter the name of the class teacher for C :Jiten
Enter the name of the class 4 :D
Enter the name of the class teacher for D :Ishmeet
Classes and their class teachers:
Class: A , Class Teacher's name: Dhruv
Class: B , Class Teacher's name: Sarthak
Class: C , Class Teacher's name: Jiten
Class: D , Class Teacher's name: Ishmeet
Enter the name of the class to find its class teacher:C
The Class Teacher of C is Jiten .
# Ques-11: Write a program to store student names and their percentages in a dictionary.
# Delete a particular student name from the dictionary.
# Also display the dictionary after deletion.

students={}
n=int(input("Enter the number of students:"))
for i in range (n):
name=input("Enter the name of the student "+str(i+1)+" :")
percentage=float(input("Enter the percentage of "+name+" :"))
students[name]=percentage
print("Original dictionary of students and their percentages:")
for name,percentage in students.items():
print("Student Name:",name,", Percentage:",percentage)
student_to_delete=input("Enter the name of the student to delete:")
if student_to_delete in students:
del students[student_to_delete]
print(student_to_delete,"has been deleted.")
else:
print("No student found with the name",student_to_delete)
print("The dictionary after deletion:")
for name,percentage in students.items():
print("Student Name:",name,", Percentage:",percentage)

Enter the number of students:4


Enter the name of the student 1 :Sarthak
Enter the percentage of Sarthak :91.2
Enter the name of the student 2 :Dhruv
Enter the percentage of Dhruv :94.8
Enter the name of the student 3 :Sukham
Enter the percentage of Sukham :94.6
Enter the name of the student 4 :Bharat
Enter the percentage of Bharat :33.5
Original dictionary of students and their percentages:
Student Name: Sarthak , Percentage: 91.2
Student Name: Dhruv , Percentage: 94.8
Student Name: Sukham , Percentage: 94.6
Student Name: Bharat , Percentage: 33.5
Enter the name of the student to delete:Sukham
Sukham has been deleted.
The dictionary after deletion:
Student Name: Sarthak , Percentage: 91.2
Student Name: Dhruv , Percentage: 94.8
Student Name: Bharat , Percentage: 33.5
# Ques-12: Write a python program to input names of 'n' customers and their details like
# items bought, cost and phone number,etc.
# Store them in a dictionary and display all the details in a tabular form.
from tabulate import tabulate
customers={}
n=int(input("Enter the number of customers:"))
for i in range(n):
name=input("\nEnter the name of customer " + str(i + 1) + ": ")
items_bought=input("Enter the items bought by " + name + " (comma-separated): ")
cost=float(input("Enter the total cost for " + name + ": "))
phone_number=input("Enter the phone number of " + name + ": ")
customers[name]={
"Items Bought": items_bought,
"Total Cost": cost,
"Phone Number": phone_number
}
table_data=[]
for name,details in customers.items():
table_data.append([name, details["Items Bought"], details["Total Cost"], details["Phone
Number"]])
print("Customer Details:")
print(tabulate(table_data, headers=["Customer Name", "Items Bought", "Total Cost", "Phone
Number"], tablefmt="grid"))

Enter the number of customers: 3


Enter the name of customer 1: Dhruv
Enter the items bought by Dhruv (comma-separated): Pen,Pencil
Enter the total cost for Dhruv: 5
Enter the phone number of Dhruv: 3256897546
Enter the name of customer 2: Sarthak
Enter the items bought by Sarthak (comma-separated): Bat,Ball
Enter the total cost for Sarthak: 510
Enter the phone number of Sarthak: 5874596563
Enter the name of customer 3: Jiten
Enter the items bought by Jiten (comma-separated): Bat,Pencil
Enter the total cost for Jiten: 503
Enter the phone number of Jiten: 5623587452
Customer Details:
+-----------------+----------------+--------------+----------------+
| Customer Name | Items Bought | Total Cost | Phone Number |
+=================+================+==============+================+
| Dhruv | Pen,Pencil | 5 | 3256897546 |
+-----------------+----------------+--------------+----------------+
| Sarthak | Bat,Ball | 510 | 5874596563 |
+-----------------+----------------+--------------+----------------+
| Jiten | Bat,Pencil | 503 | 5623587452 |
+-----------------+----------------+--------------+----------------+
# Ques-13: Write a python program to capitalize first and last letters of each word of a given
# string.

input_string=input("Enter a string: ")


words=input_string.split()
result=[]
for word in words:
if len(word)>1:
new_word=word[0].upper()+word[1:-1]+word[-1].upper()
else:
new_word=word.upper()
result.append(new_word)
output_string=' '.join(result)
print("Modified string:",output_string)

Enter a string: i am a pro at coding


Modified string: I AM A PrO AT CodinG
# Ques-14: Write a Python program to remove duplicate characters of a given string.

input_string=input("Enter a string: ")


result=""
for char in input_string:
if char not in result:
result=result+char
print("String after removing duplicates:",result)

Enter a string: 122333444455555666666


String after removing duplicates: 123456
# Ques-15: Write a Python program to compute the sum of digits of a given string.

input_string=input("Enter a string:")
sum_of_digits=0
for char in input_string:
if char.isdigit():
sum_of_digits+=int(char)
print("Sum of digits in the string:",sum_of_digits)

Enter a string: 123456


Sum of digits in the string: 21
# Ques-16: Write a Python program to find the second most repeated word in a given string.

from collections import Counter


input_string=input("Enter a string:")
words=input_string.split()
word_count=Counter(words)
most_common=word_count.most_common()
if len(most_common)>=2:
second_most_common_word=most_common[1][0]
print("The second most repeated word is:",second_most_common_word)
else:
print("There is no second most repeated word.")

Enter a string: abbccc


The second most repeated word is: b
# Ques-17: Write a Python program to change a given string to a new string where the first and
# the last characters have been exchanged.

input_string=input("Enter a string: ")


if len(input_string)>1:
new_string=input_string[-1]+input_string[1:-1]+input_string[0]
else:
new_string=input_string
print("New string:",new_string)

Enter a string: 123456


New string: 623451
# Ques-18: Write a Python program to multiply all the items in a list by 5.

input_list=[int(x) for x in input("Enter numbers separated by spaces: ").split()]


result=[x * 5 for x in input_list]
print("List after multiplying each item by 5:",result)

Enter numbers separated by spaces: 0 1 2 3 4 5 6


List after multiplying each item by 5: [0, 5, 10, 15, 20, 25, 30]
# Ques-19: Write a Python program to get the smallest number from a list of integers.

input_list=[int(x) for x in input("Enter numbers separated by spaces: ").split()]


smallest_number=min(input_list)
print("The entered list is:",input_list)
print("The smallest number is:",smallest_number)

Enter numbers separated by spaces: 1 2 3 0 4 5 6 7 8 9


The entered list is: [1, 2, 3, 0, 4, 5, 6, 7, 8, 9]
The smallest number is: 0
# Ques-20: Write a Python program to append a list to the second list.

list1=[int(x) for x in input("Enter elements for the first list separated by spaces:").split()]
list2=[int(x) for x in input("Enter elements for the second list separated by spaces:").split()]
print("The first entered list is:",list1)
print("The second entered list is:",list2)
list2.extend(list1)
print("Second list after appending:",list2)

Enter elements for the first list separated by spaces:4 3 2 1 0


Enter elements for the second list separated by spaces: 9 8 7 6 5
The first entered list is: [4, 3, 2, 1, 0]
The second entered list is: [9, 8, 7, 6, 5]
Second list after appending: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# Ques-21: Write a Python program to generate and print a list of first and last 5 elements
# where the values are squares of numbers between 1 and 30 (both included).

squares=[x**2 for x in range(1, 31)]


first_last_5=squares[:5]+squares[-5:]
print("First and last 5 elements:",first_last_5)

First and last 5 elements: [1, 4, 9, 16, 25, 676, 729, 784, 841, 900]
# Ques-22: Write a Python program to get unique values from a list.

input_list=[int(x) for x in input("Enter numbers separated by spaces: ").split()]


unique_values=list(set(input_list))
print("The entered ist is:",input_list)
print("Unique values in the list:",unique_values)

Enter numbers separated by spaces: 1 2 2 3 3 3 4 4 4 4


The entered ist is: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
Unique values in the list: [1, 2, 3, 4]
# Ques-23: Write a Python program to convert a string to a list.

input_string=input("Enter a string: ")


string_list=list(input_string)
print("The entered string is:",input_string)
print("List of characters:",string_list)

Enter a string: iamaproatcoding


The entered string is: iamaproatcoding
List of characters: ['i', 'a', 'm', 'a', 'p', 'r', 'o', 'a', 't', 'c', 'o', 'd', 'i', 'n', 'g']
# Ques-24: Write a Python script to concatenate the following dictionaries to create a new one:
# d1={‘A’:1, ‘B’:2 , ‘C’:3}
# d2={‘D’:4}
# Output should be :
# {‘A’:1, ‘B’:2, ‘C’:3, ‘D’:4}.

d1={'A': 1, 'B': 2, 'C': 3}


d2={'D': 4}
d3={**d1,**d2}
print("The given dictionaries are",d1,"and",d2)
print("The new dictionary is",d3)

The given dictionaries are {'A': 1, 'B': 2, 'C': 3} and {'D': 4}


The new dictionary is {'A': 1, 'B': 2, 'C': 3, 'D': 4}
# Ques-25: Write a Python script to check if a given key already exists in a dictionary.

d={'A': 1,'B': 2,'C': 3}


key=input("Enter the key to check:")
if key in d:
print(f"Key '{key}' exists in the dictionary.")
else:
print(f"Key '{key}' does not exist in the dictionary.")

Enter the key to check:C


Key 'C' exists in the dictionary.
# Ques-26: Create a binary file student with name roll number and marks. Search for a given roll
# number and display the name and marks, if not found display appropriate message.

import pickle
students=[]
n=int(input("Enter the number of students: "))
for _ in range(n):
name = input("Enter student's name: ")
roll_no = int(input("Enter roll number: "))
marks = float(input("Enter marks: "))
students.append({'name': name, 'roll_no': roll_no, 'marks': marks})
with open('students.dat', 'wb') as file:
pickle.dump(students, file)
def search_student(roll_no):
with open('students.dat', 'rb') as file:
students = pickle.load(file)
for student in students:
if student['roll_no'] == roll_no:
return student
return None
roll_no=int(input("Enter roll number to search: "))
student=search_student(roll_no)
if student:
print(f"Student Found: Name = {student['name']}, Marks = {student['marks']}")
else:
print("Student not found!")

Enter the number of students: 2


Enter student's name: Dhruv
Enter roll number: 1
Enter marks: 95
Enter student's name: Saksham
Enter roll number: 2
Enter marks: 95
Enter roll number to search: 1
Student Found: Name = Dhruv, Marks = 95.0
# Ques-27: Write a Program to increase 5 marks of each student in the above student data file.

import pickle
students=[]
n=int(input("Enter the number of students: "))
for _ in range(n):
name = input("Enter student's name: ")
roll_no = int(input("Enter roll number: "))
marks = float(input("Enter marks: "))
students.append({'name': name, 'roll_no': roll_no, 'marks': marks})
with open('students.dat', 'wb') as file:
pickle.dump(students, file)
for student in students:
student['marks']+=5
with open('students.dat','wb') as file:
pickle.dump(students,file)
print("Marks of all students have been increased by 5.")
for student in students:
print(f"Name:{student['name']},Roll No:{student['roll_no']},Updated Marks:{student['marks']}")

Enter the number of students: 2


Enter student's name: Dhruv
Enter roll number: 1
Enter marks: 95
Enter student's name: Saksham
Enter roll number: 2
Enter marks: 95
Marks of all students have been increased by 5.
Name: Dhruv, Roll No: 1, Updated Marks: 100.0
Name: Saksham, Roll No: 2, Updated Marks: 100.0
# Ques-28: Create a text file employee to store information such as ID, name, department,
# salary. Display details of all the employees.

n=int(input("Enter the number of employees: "))


with open('employee.txt', 'w') as file:
for _ in range(n):
emp_id=input("Enter employee ID:")
name=input("Enter employee name:")
department=input("Enter department:")
salary=float(input("Enter salary:"))
file.write(f"ID:{emp_id},Name:{name},Department:{department},Salary:{salary}\n")
with open('employee.txt','r') as file:
print("\nEmployee Details:")
for line in file:
print(line.strip())

Enter the number of employees: 2


Enter employee ID: 001
Enter employee name: Dhruv
Enter department: Tech
Enter salary: 5000000
Enter employee ID: 002
Enter employee name: Saksham
Enter department: Peon
Enter salary: 8000

Employee Details:
ID: 001, Name: Dhruv, Department: Tech, Salary: 5000000.0
ID: 002, Name: Saksham, Department: Peon, Salary: 8000.0
# Ques-29: Create code to ask the user to enter department name then count total number of
# employees and total salary paid to a department from the above data file employee.

n=int(input("Enter the number of employees:"))


with open('employee.txt', 'w') as file:
for _ in range(n):
emp_id=input("Enter employee ID:")
name=input("Enter employee name:")
department=input("Enter department:")
salary=float(input("Enter salary:"))
file.write(f"ID: {emp_id}, Name: {name}, Department: {department}, Salary: {salary}\n")
department_name=input("Enter department name to search:")
total_employees=0
total_salary=0
with open('employee.txt', 'r') as file:
for line in file:
data=line.strip().split(", ")
department=data[2].split(": ")[1]
salary=float(data[3].split(": ")[1])
if department==department_name:
total_employees+=1
total_salary+=salary
if total_employees>0:
print(f"Total number of employees in {department_name}: {total_employees}")
print(f"Total salary paid to {department_name}: {total_salary}")
else:
print(f"No employees found in {department_name} department.")

Enter the number of employees: 2


Enter employee ID: 001
Enter employee name: Dhruv
Enter department: Tech
Enter salary: 500000
Enter employee ID: 002
Enter employee name: Saksham
Enter department: Clerk
Enter salary: 6000
Enter department name to search: Clerk
Total number of employees in Clerk: 1
Total salary paid to Clerk: 6000.0
# Ques-30: Write code to ask the user to enter employee ID then erase data from the employee
# data file.

employee_id_to_remove=input("Enter employee ID to remove: ")


with open('employee.txt', 'r') as file:
lines = file.readlines()
with open('employee.txt', 'w') as file:
for line in lines:
if f"ID: {employee_id_to_remove}" not in line:
file.write(line)
print(f"Employee with ID {employee_id_to_remove} has been removed.")

Enter employee ID to remove: 002


Employee with ID 002 has been removed.
# Ques-31: Create MySQL connectivity program in Python to insert a record in table library in
# database school.(record to be inserted is book_id,book_name,author, booked).

import mysql.connector
connection=mysql.connector.connect(
host="localhost",
user="root",
password="123",
database="school"
)
book_id=input("Enter Book ID:")
book_name=input("Enter Book Name:")
author=input("Enter Author Name:")
booked=input("Enter Booked status (1 for Yes, 0 for No):")
cursor=connection.cursor()
cursor.execute(
"INSERT INTO library (book_id, book_name, author, booked) VALUES (%s, %s, %s, %s)",
(book_id, book_name, author, booked)
)
connection.commit()
print("Record added successfully.")
connection.close()
print("Connection closed.")

Enter Book ID: 102


Enter Book Name: Data Science Basics
Enter Author Name: Jane Smith
Enter Booked status (1 for Yes, 0 for No): 1
Record added successfully.
Connection closed.
# Ques-32: Create MySql connectivity program in Python to update status of book as booked or
# available in the table library database name is school.

import mysql.connector
connection=mysql.connector.connect(
host="localhost",
user="root",
password="123",
database="school"
)
book_id=input("Enter the Book ID to update:")
new_status=input("Enter new status (1 for booked, 0 for available):")
cursor=connection.cursor()
cursor.execute(
"UPDATE library SET booked = %s WHERE book_id=%s",
(new_status, book_id)
)
connection.commit()
print("Book status updated successfully.")
connection.close()
print("Connection closed.")

Enter the Book ID to update: 102


Enter new status (1 for booked, 0 for available): 1
Book status updated successfully.
Connection closed.
# Ques-33: Create a MySql connectivity program in Python to delete a book detail from the
# library table in database school.

import mysql.connector
connection=mysql.connector.connect(
host="localhost",
user="root",
password="123",
database="school"
)
book_id=input("Enter the Book ID to delete:")
cursor=connection.cursor()
cursor.execute(
"DELETE FROM library WHERE book_id=%s",
(book_id,)
)
connection.commit()
print("Book record deleted successfully.")
connection.close()
print("Connection closed.")

Enter the Book ID to delete: 102


Book record deleted successfully.
Connection closed.
# Ques-34: Create MySql connectivity program to display all book details from the library table
# of database school.

import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="school"
)
cursor=connection.cursor()
cursor.execute("SELECT * FROM library")
records=cursor.fetchall()
print("Book Details:")
for row in records:
print(row)
connection.close()
print("Connection closed.")

Book Details:
(101, 'Python Programming', 'John Doe', Booked)
(102, 'Data Science Basics', 'Jane Smith', Unbooked)
(103, 'Machine Learning', 'Alice Brown', Booked)
(104, 'Deep Learning', 'Bob Clark', Unbooked)
Connection closed.
# Ques-35: Create MySql connectivity program to search the details of a book from the library
# table of database school on the basis of Book_Id.

import mysql.connector
connection=mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="school"
)
book_id=input("Enter the Book ID to search:")
cursor=connection.cursor()
cursor.execute("SELECT * FROM library WHERE book_id = %s",(book_id,))
record=cursor.fetchone()
if record:
print("Book Details:")
print(f"Book ID: {record[0]}")
print(f"Book Name: {record[1]}")
print(f"Author: {record[2]}")
print(f"Booked Status: {'Booked' if record[3] == 1 else 'Available'}")
else:
print("No book found with that Book ID.")
connection.close()
print("Connection closed.")

Enter the Book ID to search: 102


Book Details:
Book ID: 102
Book Name: Data Science Basics
Author: Jane Smith
Booked Status: Available
Connection closed.

You might also like