0% found this document useful (0 votes)
73 views56 pages

Cs Practical

The document contains a student's practical file with questions and solutions related to functions, data files, and MySQL in Python. It includes 5 questions on working with functions with solutions, 3 questions on manipulating data files with solutions, and 1 question on searching a binary student data file with solutions. The file contains an index with the question numbers and pages for each chapter.
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)
73 views56 pages

Cs Practical

The document contains a student's practical file with questions and solutions related to functions, data files, and MySQL in Python. It includes 5 questions on working with functions with solutions, 3 questions on manipulating data files with solutions, and 1 question on searching a binary student data file with solutions. The file contains an index with the question numbers and pages for each chapter.
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/ 56

CS

PRACTICAL FILE

NAME: Nagmani
CLASS: XII-A
ROLL NO: 16
INDEX
S. Teachers
NO CHAPTER Questions Page
. sign

Working with
1 Q1 - Q5 Pg.4 - Pg.8
Functions

2 Data Files Q6 - Q13 Pg.10 - Pg.44

4 MySQL Q16-Q18 Pg.45-Pg.51


Working
with
Functions
1. WAP that generates a series using a function which
takes first and the last value of the series. And then
generates
four terms that are equidistant. Eg. if two numbers
passed are 1 and 7 then function returns 1 3 5 7.
Display the error message if equidistant numbers
cannot be formed
Sol:- Code
def gen_series(first, last):
if (last - first) % 6 != 0:
print("Error: Equidistant numbers cannot be formed.")
return

difference = (last - first) // 6


series = [first]
for i in range(1, 4):
series.append(first + (i * 2 * difference))
return series

f = int(input("Enter the first value: "))


l = int(input("Enter the last value: "))
eq_series = gen_series(f, l)
if eq_series:
print("Equidistant Series:", ' '.join(map(str, eq_series)))

Output
2. The function REV( ) that accept a line of text as
argument and returns the line in which each word is
reversed. Display both original and reversed line of
text.
Sol:- Code

def rev(line):
words = line.split()
reversed_line = ' '.join(w[::-1] for w in words)
return reversed_line

txt = input("Enter a line of text: ")


rev_txt = rev(txt)

print("Original: ", txt)


print("Reversed: ", rev_txt)

Output
3. WAP to accept the list and sort it in ascending order
using bubble sort.
Sol:- Code
def bubble_sort(lst):
n = len(lst)
for i in range(n):
for j in range(n - i - 1):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]

nums = list(map(int, input("Enter a list of numbers: ").split()))


bubble_sort(nums)
print("Sorted List (Ascending):", nums)

Output
4. WAP to accept the list and sort it in descending order
using insertion sort

Sol:- Code
def insertion_sort(lst):
n = len(lst)
for i in range(1, n):
key = lst[i]
j=i-1
while j >= 0 and lst[j] < key:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = key

nums = list(map(int, input("Enter a list of numbers: ").split()))


insertion_sort(nums)
print("Sorted List (Descending):", nums)

Output
5. The function to find and display all the prime
numbers between 2 to N, where N is passed as
argument to the function.
Sol:- Code
def find_primes(n):
primes = []
for num in range(2, n + 1):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
primes.append(num)
return primes

N = int(input("Enter the value of N: "))


prime_nums = find_primes(N)
print("Prime numbers between 2 and", N, "are:", prime_nums)

Output
Data Files
6. WA menu Driven program to perform the following tasks for the
file STUDENT.TXT:
a. Create
b. Display Whole File
c. Display Words Which Begins With Uppercase Alphabets
d. Exit
# Create: will accept the line of text from the user and write in the
file.
# Display Whole File: will display the entire content from the file.
# Display Words Which Begins With Uppercase Alphabets: will display
those words which begins with uppercase alphabets.
Sol:- Code
def create_file():
text = input("Enter a line of text: ")
with open("STUDENT.TXT", "w") as file:
file.write(text)
print("File created successfully.")

def display_file():
with open("STUDENT.TXT", "r") as file:
content = file.read()
print("File Content:\n", content)

def display_uppercase_words():
with open("STUDENT.TXT", "r") as file:
content = file.read()
words = content.split()
uppercase_words = [word for word in words if word[0].isupper()]
print("Words beginning with uppercase alphabets:\n", uppercase_words)

while True:
print("\nMenu:")
print("a. Create")
print("b. Display Whole File")
print("c. Display Words Which Begins With Uppercase Alphabets")
print("d. Exit")
choice = input("Enter your choice (a, b, c, or d): ")

if choice == 'a':
create_file()
elif choice == 'b':
display_file()
elif choice == 'c':
display_uppercase_words()
elif choice == 'd':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

Output
7. WA menu Driven program to perform the following
tasks for the above created file STUDENT.TXT:
a. Remove
b. Convert Case
c. Exit
# Remove Word: will delete the word entered by the
user from the file.
# Convert Case: will convert each character to its
opposite case
Sol:- Code

def remove_word(file, word):


with open(file, 'r+') as f:
lines = f.readlines()
f.seek(0)
for line in lines:
new_line = ' '.join([w for w in line.split() if w != word])
f.write(new_line + '\n')
f.truncate()

def convert_case(file):
with open(file, 'r+') as f:
content = f.read()
f.seek(0)
f.write(content.swapcase())
f.truncate()

def display_menu():
print("Menu:")
print("a. Remove Word")
print("b. Convert Case")
print("c. Exit")
filename = "STUDENT.TXT"
while True:
display_menu()
choice = input("Enter your choice (a, b, or c): ")

if choice == 'a':
word = input("Enter the word to remove: ")
remove_word(filename, word)
print("Word removed successfully.")

elif choice == 'b':


convert_case(filename)
print("Case converted successfully.")

elif choice == 'c':


print("Exiting the program.")
break

else:
print("Invalid choice. Please try again.")

Output
8. WA menu Driven program to perform the following
tasks for the file DATA.TXT:
a. Create
b. Display all
c. Shift Data
d. Exit
# Create: will accept the line of text from the user and
write in the file.
# Display all: will display the entire content from the
file. The name of the file is entered as an argument to
the function.
# Shift Data: will transfer all the uppercase characters
in UPPER.TXT, all lowercase characters in LOWER.TXT
and all digits in DIGIT.TXT
Sol:- Code
def create_file():
txt = input("Enter a line of text: ")
with open("DATA.TXT", "w") as f:
f.write(txt)
print("File created successfully.")

def display_all(file):
with open(file, "r") as f:
content = f.read()
print("File Content:\n", content)

def shift_data():
with open("DATA.TXT", "r") as f:
content = f.read()
upper = ''
lower = ''
digits = ''
for char in content:
if char.isupper():
upper += char
elif char.islower():
lower += char
elif char.isdigit():
digits += char

with open("UPPER.TXT", "w") as f:


f.write(upper)
with open("LOWER.TXT", "w") as f:
f.write(lower)
with open("DIGIT.TXT", "w") as f:
f.write(digits)

print("Data shifted successfully.")

while True:
print("\nMenu:")
print("a. Create")
print("b. Display all")
print("c. Shift Data")
print("d. Exit")

choice = input("Enter your choice (a, b, c, or d): ")

if choice == 'a':
create_file()
elif choice == 'b':
display_all("DATA.TXT")
elif choice == 'c':
shift_data()
elif choice == 'd':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
Output
9. Write a menu driven program to perform the
following tasks for a binary file STUDENT.DAT
containing the following structure: [rno, name, marks,
grade]
1. Create
2. Display
3. Calculate Grade
4. Search
5. Exit
#Create: must ask the user to enter roll number, name
and marks(out of 500) for the student and write into
the file.
#Display: must display each record on separate line in
the following format:
<rno>, <names>has scored grade <grade>
If grade is not calculated display () function must
display the following message:
“Grade not calculated. No record to display”

#Calculate Grade: must calculate the grade of each


record using the following table:

#Search: must ask roll number and display the details


of that student if exists, otherwise error message
“Record Not Found” must be displayed.
Sol:- Code
class S:
def __init__(self, f):
self.f = f

def c(self):
r = int(input("Enter roll number: "))
n = input("Enter name: ")
m = int(input("Enter marks (out of 500): "))
with open(self.f, "a") as f:
f.write(f"{r},{n},{m}\n")
print("Record created successfully.")

def d(self):
with open(self.f, "r") as f:
c = f.readlines()
if c:
for l in c:
r, n, m = l.strip().split(',')
print(f"{r} , {n} has scored grade {self.g(int(m))}")
else:
print("Grade not calculated. No record to
display.")

def g(self, m):


if 90 <= m <= 100:
return "A"
elif 80 <= m < 90:
return "B+"
elif 70 <= m < 80:
return "B"
elif 60 <= m < 70:
return "C+"
elif 50 <= m < 60:
return "C"
else:
return "F"

def s(self, r):


f = False
with open(self.f, "r") as f:
c = f.readlines()
for l in c:
sr, n, m = l.strip().split(',')
if int(sr) == r:
f = True
print(f"Roll Number: {sr}, Name: {n}, Marks: {m}")
break
if not f:
print("Record Not Found")

f = "S.DAT"
s = S(f)

while True:
print("\nMenu:")
print("1. Create")
print("2. Display")
print("3. Calculate Grade")
print("4. Search")
print("5. Exit")
c = int(input("Enter your choice (1-5): "))
if c == 1:
s.c()
elif c == 2:
s.d()
elif c == 3:
m = int(input("Enter marks: "))
print(f"Grade: {s.g(m)}")
elif c == 4:
r = int(input("Enter roll number: "))
s.s(r)
elif c == 5:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
Output
10. Write a menu driven program to perform the
following tasks for the above created binary file
STUDENT.DAT.
1. Create
2. Display
3. Search
4. Modify
5. Delete
6. Exit
#Create: must ask the user to enter roll number, name
and marks(out of 500) for the student and write into
the file.
#Display: must display each record on separate line in
the following format:
<rno>, <names>has scored grade <grade>
If grade is not calculated display () function must
display the following message:
“Grade not calculated. No record to display”
#Modify: must ask roll number of the student and
modify the remaining details after taking confirmation
from the user.
#Delete: must ask roll number of the student and
delete the record after taking confirmation from the
user.
Sol:- Code
'''class StudentFile:
def __init__(self, filename):
self.filename = filename

def create(self):
rno = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = int(input("Enter marks (out of 500): "))
with open(self.filename, "a") as file:
file.write(f"{rno},{name},{marks}\n")
print("Record created successfully.")

def display(self):
with open(self.filename, "r") as file:
content = file.readlines()
if content:
for line in content:
rno, name, marks = line.strip().split(',')
print(f"{rno} , {name} has scored grade
{self.calculate_grade(int(marks))}")
else:
print("Grade not calculated. No record to
display.")

def calculate_grade(self, marks):


if 90 <= marks <= 100:
return "A"
elif 80 <= marks < 90:
return "B+"
elif 70 <= marks < 80:
return "B"
elif 60 <= marks < 70:
return "C+"
elif 50 <= marks < 60:
return "C"
else:
return "F"

def search(self, rno):


found = False
with open(self.filename, "r") as file:
content = file.readlines()
for line in content:
s_rno, name, marks = line.strip().split(',')
if int(s_rno) == rno:
found = True
print(f"Roll Number: {s_rno}, Name: {name},
Marks: {marks}")
break
if not found:
print("Record Not Found")

filename = "STUDENT.DAT"
sf = StudentFile(filename)
while True:
print("\nMenu:")
print("1. Create")
print("2. Display")
print("3. Calculate Grade")
print("4. Search")
print("5. Exit")
choice = int(input("Enter your choice (1-5): "))

if choice == 1:
sf.create()
elif choice == 2:
sf.display()
elif choice == 3:
marks = int(input("Enter marks: "))
print(f"Grade: {sf.calculate_grade(marks)}")
elif choice == 4:
rno = int(input("Enter roll number: "))
sf.search(rno)
elif choice == 5:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")'''

class StudentFile:
def __init__(self, filename):
self.filename = filename
def create(self):
rno = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = int(input("Enter marks (out of 500): "))
with open(self.filename, "a") as file:
file.write(f"{rno},{name},{marks}\n")
print("Record created successfully.")

def display(self):
with open(self.filename, "r") as file:
content = file.readlines()
if content:
for line in content:
rno, name, marks = line.strip().split(',')
print(f"{rno} , {name} has scored grade
{self.calculate_grade(int(marks))}")
else:
print("Grade not calculated. No record to display.")

def calculate_grade(self, marks):


if 90 <= marks <= 100:
return "A"
elif 80 <= marks < 90:
return "B+"
elif 70 <= marks < 80:
return "B"
elif 60 <= marks < 70:
return "C+"
elif 50 <= marks < 60:
return "C"
else:
return "F"

def search(self, rno):


found = False
with open(self.filename, "r") as file:
content = file.readlines()
for line in content:
s_rno, name, marks = line.strip().split(',')
if int(s_rno) == rno:
found = True
print(f"Roll Number: {s_rno}, Name: {name}, Marks: {marks}")
break
if not found:
print("Record Not Found")

def modify(self):
rno = int(input("Enter roll number to modify: "))
found = False
with open(self.filename, "r") as file:
content = file.readlines()
for i, line in enumerate(content):
s_rno, name, marks = line.strip().split(',')
if int(s_rno) == rno:
found = True
new_name = input("Enter new name: ")
new_marks = int(input("Enter new marks (out of 500): "))
content[i] = f"{rno},{new_name},{new_marks}\n"
with open(self.filename, "w") as file:
file.writelines(content)
print("Record modified successfully.")
break
if not found:
print("Record Not Found")

def delete(self):
rno = int(input("Enter roll number to delete: "))
found = False
with open(self.filename, "r") as file:
content = file.readlines()
for i, line in enumerate(content):
s_rno, name, marks = line.strip().split(',')
if int(s_rno) == rno:
found = True
confirmation = input("Are you sure you want to delete this record? (yes/no): ")
if confirmation.lower() == "yes":
del content[i]
with open(self.filename, "w") as file:
file.writelines(content)
print("Record deleted successfully.")
else:
print("Deletion cancelled.")
break
if not found:
print("Record Not Found")

def menu(self):
while True:
print("\nMenu:")
print("1. Create")
print("2. Display")
print("3. Search")
print("4. Modify")
print("5. Delete")
print("6. Exit")
choice = int(input("Enter your choice (1-6): "))

if choice == 1:
self.create()
elif choice == 2:
self.display()
elif choice == 3:
rno = int(input("Enter roll number: "))
self.search(rno)
elif choice == 4:
self.modify()
elif choice == 5:
self.delete()
elif choice == 6:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

filename = "STUDENT.DAT"
sf = StudentFile(filename)
sf.menu()
Output
11. Write a Menu Driven Program to create a csv file
named student.csv containing rollnumber, name and
phone number. The menu is as follows:
a. Read
b. Write
c. Search
d. Exit
#Read: must read the entire file and display it on the
screen.
#Write: must take valid input from the user and write
into the file.
#Search: must display the details of those students
whose name is entered as the parameter to the
Search() function.

Sol:- Code
import csv

class StudentCSV:
def __init__(self, filename):
self.filename = filename

def read(self):
try:
with open(self.filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(','.join(row))
except FileNotFoundError:
print("File not found.")
def write(self, rno, name, phone):
with open(self.filename, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([rno, name, phone])
print("Record written successfully.")

def search(self, name):


found = False
try:
with open(self.filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
if name.lower() in row[1].lower():
found = True
print(f"Roll Number: {row[0]}, Name:
{row[1]}, Phone: {row[2]}")
break
if not found:
print("No record found.")
except FileNotFoundError:
print("File not found.")

def menu(self):
while True:
print("\nMenu:")
print("a. Read")
print("b. Write")
print("c. Search")
print("d. Exit")
choice = input("Enter your choice (a-d): ")
if choice == 'a':
self.read()
elif choice == 'b':
rno = int(input("Enter roll number: "))
name = input("Enter name: ")
phone = input("Enter phone number: ")
self.write(rno, name, phone)
elif choice == 'c':
name = input("Enter name to search: ")
self.search(name)
elif choice == 'd':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

filename = "student.csv"
sc = StudentCSV(filename)
sc.menu()
Output
12. Write a Menu Driven Program to perform the
following tasks in the above created csv file named
student.csv. The menu is as follows:
a. Read
b. Write
c. Modify
d. Delete
e. Exit
#Read: must read the entire file and display it on the
screen.
#Write: must take valid input from the user and write
into the file.
#Modify: must ask roll number of the student and
modify the remaining details after taking confirmation
from the user.
#Delete: must ask roll number of the student and
delete the record after taking confirmation from the
user.

Sol:- Code
import csv

def read_file(filename):
with open(filename, 'r', newline='') as file:
reader = csv.reader(file)
for row in reader:
print(','.join(row))

def write_file(filename, data):


with open(filename, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(data)
print("Record written successfully.")
def modify_record(filename, roll_number):
with open(filename, 'r', newline='') as file:
rows = list(csv.reader(file))

found = False
for i, row in enumerate(rows):
if row[0] == roll_number:
print("Existing Record:")
print(','.join(row))
print("Enter new details:")
name = input("Enter new name: ")
phone = input("Enter new phone number: ")
rows[i] = [roll_number, name, phone]
found = True
break

if found:
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(rows)
print("Record modified successfully.")
else:
print("Record not found.")

def delete_record(filename, roll_number):


with open(filename, 'r', newline='') as file:
rows = list(csv.reader(file))
found = False
for i, row in enumerate(rows):
if row[0] == roll_number:
print("Deleting Record:")
print(','.join(row))
del rows[i]
found = True
break

if found:
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(rows)
print("Record deleted successfully.")
else:
print("Record not found.")

while True:
print("\nMenu:")
print("1. Read")
print("2. Write")
print("3. Modify")
print("4. Delete")
print("5. Exit")

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


if choice == '1':
read_file("student.csv")
elif choice == '2':
roll_number = input("Enter roll number: ")
name = input("Enter name: ")
phone = input("Enter phone number: ")
write_file("student.csv", [roll_number, name,
phone])
elif choice == '3':
roll_number = input("Enter roll number to modify: ")
modify_record("student.csv", roll_number)
elif choice == '4':
roll_number = input("Enter roll number to delete: ")
delete_record("student.csv", roll_number)
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
Output
13. Write a Menu Driven Program to perform the
following tasks in the csv file named id.csv. The menu is
as follows:
a. Create
b. Display All
c. Search
d. Exit

#Create: must ask the userid and password from the


user and write it into id.csv only if it is valid. The
validity is checked according to the following rule:
• Userid must contain @ symbol
• It should end with either .com or .co.in
• It must be unique
#Search: must ask the user the user id and display the
respective password.
#DisplayAll: must display the entire file where each
record is display on separate line along with the record
number.

Sol:- Code
class UserDatabase:
def __init__(self, filename):
self.filename = filename

def create(self, userid, password):


if '@' in userid and (userid.endswith('.com') or
userid.endswith('.co.in')):
try:
with open(self.filename, 'a') as file:
file.write(f"{userid},{password}\n")
print("User created successfully.")
except Exception as e:
print("Error:", e)
else:
print("Invalid user ID format.")

def search(self, userid):


found = False
try:
with open(self.filename, 'r') as file:
for line in file:
entry = line.strip().split(',')
if entry[0] == userid:
found = True
print(f"User ID: {entry[0]}, Password:
{entry[1]}")
break
if not found:
print("User not found.")
except FileNotFoundError:
print("File not found.")

def display_all(self):
try:
with open(self.filename, 'r') as file:
for i, line in enumerate(file, 1):
entry = line.strip().split(',')
print(f"Record {i}: User ID: {entry[0]},
Password: {entry[1]}")
except FileNotFoundError:
print("File not found.")
def menu(self):
while True:
print("\nMenu:")
print("a. Create")
print("b. Display All")
print("c. Search")
print("d. Exit")
choice = input("Enter your choice (a-d): ")

if choice == 'a':
userid = input("Enter user ID: ")
password = input("Enter password: ")
self.create(userid, password)
elif choice == 'b':
self.display_all()
elif choice == 'c':
userid = input("Enter user ID to search: ")
self.search(userid)
elif choice == 'd':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

filename = "id.csv"
ud = UserDatabase(filename)
ud.menu()
Output
MySQL
16. Consider the following tables GAMES and PLAYER
and answer (b) and (c) parts of this question:

(b) Write SQL commands for the flowing statements:


(i) To display the name of all GAMES with their GCodes
Sol:- Code
SELECT GCode, GameName FROM GAMES;

(ii) To display details of those GAMES which are having


PrizeMoney more than 7000.
Sol:- Code
SELECT *FROM GAMES WHERE PrizeMoney > 7000;
(iii) To display the content of the GAMES table in
ascending order of Schedule Date.
Sol:- Code
SELECT *FROM GAMES ORDER BY ScheduleDate ASC;

(iv) To display sum of PrizeMoney for each Type of GAMES


Sol:- Code
SELECT Type, SUM(PrizeMoney) AS TotalPrizeMoney FROM
GAMES GROUP BY Type;
17. Consider the following tables Stationary and
Consumer. Write SQL commands for the statement (i)
to (iv) and output for SQL queries (v) to (viii):

(i) To display the details of those consumers whose


Address is Delhi.
Sol:- Code
SELECT *FROM consumer WHERE Address = 'Delhi';

(ii) To display the details of Stationary whose Price is in the


range of 8 to 15. (Both Value included)
Sol:- Code
SELECT *FROM Stationary WHERE Price BETWEEN 8 AND 15;
(iii) To display the ConsumerName, Address from Table
Consumer, and Company and Price from table Stationary,
with their corresponding matching S_ID.
Sol:- Code
SELECT C.ConsumerName, C.Address, S.Company, S.Price
FROM Consumer C JOIN Stationary S ON C.S_ID = S.S_ID;

(iv) To increase the Price of all stationary by 2.


Sol:- Code
UPDATE Stationary SET Price = Price + 2;
18. Consider the following table RESORT and OWNER
and answer questions (A) and (B)

(A) Write SQL commands for the following statements:


(i) to display the RCODE and PLACE of all ‘2 Star’
resorts in the alphabetical order of the place from
table RESORT.
Sol:- Code

SELECT RCODE, PLACE


FROM RESORT
WHERE TYPE = '2 Star'
ORDER BY PLACE;
(ii) to display the maximum & minimum rent for each type
of resort from table RESORT.
Sol:- Code
SELECT TYPE, MAX(RENT) AS MaximumRent, MIN(RENT) AS
MinimumRent
FROM RESORT
GROUP BY TYPE;

(iii) to display the details of all resorts which are started


after 31-Dec-04 from table RESORT.
Sol:- Code
SELECT *
FROM RESORT
WHERE STARTDATE > '2004-12-31';

(iv) to display the owner of all ‘5 Star’ resorts from tables


RESORT and OWNEDBY.
Sol:- Code
SELECT R.RCODE, R.PLACE, O.OWNER
FROM RESORT R
JOIN OWNEDBY O ON R.PLACE = O.PLACE
WHERE R.TYPE = '5 Star';
19. Perform the following operations:

a. Create Database TESTDB


Sol:- Code
import sqlite3
db_conn = sqlite3.connect('TESTDB.db')
print("Database TESTDB created successfully.")

b. Open Database TESTDB


Sol:- Code
db_conn = sqlite3.connect('TESTDB.db')
print("Opened database TESTDB successfully.")

c. Create Table EMP with the following structure:

Sol:- Code
db_conn.execute('''CREATE TABLE EMP
(Empno INTEGER PRIMARY KEY,
Ename TEXT,
Age INTEGER,
Gender TEXT,
Salary REAL);''')
print("Table EMP created successfully.")
d. Insert 5 records into EMP table
Sol:- Code
emp_data = [
(1, 'John Doe', 30, 'M', 50000.0),
(2, 'Jane Smith', 28, 'F', 45000.0),
(3, 'Michael Johnson', 35, 'M', 60000.0),
(4, 'Emily Brown', 32, 'F', 55000.0),
(5, 'David Wilson', 33, 'M', 58000.0)
]
db_conn.executemany('INSERT INTO EMP
(Empno, Ename, Age, Gender, Salary)
VALUES (?, ?, ?, ?, ?)', emp_data)
db_conn.commit()
print("Records inserted successfully.")
e. Display all the records of EMP table whose Empno is
entered by the user.
Sol:- Code
empno = int(input("Enter Empno to display records: "))
cursor = db_conn.execute(f"'SELECT * FROM EMP WHERE
Empno = {empno}"')
row = cursor.fetchone()
if row:
print("Empno:", row[0])
print("Ename:", row[1])
print("Age:", row[2])
print("Gender:", row[3])
print("Salary:", row[4])
else:
print("No record found for the entered Empno.")

db_conn.close()
Output
20. Perform the following operations on EMP table:

a. Display all the records of EMP table whose Ename is


entered by the user.
Sol:- Code
import sqlite3
db_conn = sqlite3.connect('TESTDB.db')
print("Opened database TESTDB successfully.")
ename_input = input("Enter Ename to display records: ")
cursor = db_conn.execute(f"'SELECT * FROM EMP WHERE
Ename = '{ename_input}'")
rows = cursor.fetchall()
if rows:
print("Records with Ename", ename_input, ":")
for row in rows:
print("Empno:", row[0])
print("Ename:", row[1])
print("Age:", row[2])
print("Gender:", row[3])
print("Salary:", row[4])
else:
print("No records found for the entered Ename.")

b. Update age of an employee of EMP table whose Ename


starts with ‘A’ and ends with ‘a’.
Sol:- Code

db_conn.execute("UPDATE EMP SET Age = Age + 1 WHERE Ename LIKE 'A%a'")


db_conn.commit()
print("Age updated for employees with Ename starting with 'A' and ending with 'a'.")
c. Delete all the records of EMP table whose Empno is
entered by the user.
Sol:- Code
empno_input = int(input("Enter Empno to delete records: "))
db_conn.execute(f"'DELETE FROM EMP WHERE
Empno = {empno_input}'")
db_conn.commit()
print("Records with Empno", empno_input, "deleted.")

d. Close the connection to the database TESTDB.


Sol:- Code
db_conn.close()
print("Connection to database TESTDB closed.")

Output

You might also like