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

Class Xii Computer Science Practical Programs - 2022-23 2

The document provides details about practical programming assignments for Class 12. It includes 8 programming tasks - reading and processing text files, working with binary and CSV files, random number generation, and menu driven programs. The tasks involve concepts like file handling, string processing, binary data storage using pickle, CSV file operations, and random number generation.

Uploaded by

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

Class Xii Computer Science Practical Programs - 2022-23 2

The document provides details about practical programming assignments for Class 12. It includes 8 programming tasks - reading and processing text files, working with binary and CSV files, random number generation, and menu driven programs. The tasks involve concepts like file handling, string processing, binary data storage using pickle, CSV file operations, and random number generation.

Uploaded by

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

CLASS XII PRACTICAL LIST (2022-23)

1. Read a text file line by line and display each word separated by a #.
file=open("textfile_ linebyline.txt", "r")
lines=file.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+'#', end="")
print(" ")
file.close()
OUTPUT:

2. Read a text file and display the number of vowels/consonants/uppercase/lowercase characters in the
file.
'''STEPS:
1. Open the file in read mode using open().
2. Read the content of the file using rad().
3. You need to write the logic for counting the Vowels, Consonants, Ucase letters, Lower Case letters.
[islower(), isupper(), ch in [‘a’,’e’, ‘I’,’o’,’u’] and ch in[‘b’, ‘c’,’d’ etc]
4. Print the counting data.'''

file=open("Upper_lower_consonants.txt", "r")
content=file.read()
print(content)
vowels=0
consonants=0
lower_case_letters=0
upper_case_letters=0
for ch in content:
if(ch.islower()):
lower_case_letters+=1
elif(ch.isupper()):
upper_case_letters+=1
ch=ch.lower()
if (ch in ['a','e','i','o','u','A','E','I','I','U']):
vowels+=1
elif (ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']):
consonants+=1
file.close()
print("Vowels are:", vowels)
print("Consonants are:", consonants)
print("Lower case letters are:", lower_case_letters)
print("Upper case letters are:", upper_case_letters)
OUTPUT:

1
3. Remove all the lines that contain the character 'a' in a file and write it to another file.
'''STEPS:
You are supposed to read a file and remove all the lines from the file that contains and remove line should be copied
into another file.
1. we need to read this file line by line.
2. Check whether the line contains character ‘a’ anywhere.
2. If line contains character ‘a’ then remove/delete this line from ‘text.txt’ file and store/save it into some other file
‘text1.txt’.'''

file=open('remove_character_a.txt', "r")
lines=file.readlines()
file.close()
file=open('remove_character_a.txt', "w")
file1=open('remove_character_a1.txt', "w")
for line in lines:
if 'a' in line:
file1.write(line)
else:
file.write(line)
print("All line that contains a character has been removed from remove_character_a.txt")
print("All line that contains a character has been saved in remove_character_a1.txt")
file.close()
file1.close()
OUTPUT:

2
4. Create a binary file with name and roll number. Search for a given roll number and display the name,
if not found display appropriate message.
#For entering into binary file
import pickle
stud_data={}
list_of_students=[]
no_of_students=int(input("Enter no of students:"))
for i in range(no_of_students):
stud_data["roll_no"]=int(input("Enter roll no:"))
stud_data["name"]=input("Enter name:")
list_of_students.append(stud_data)
stud_data={}
file=open("stud_data.dat","wb")
pickle.dump(list_of_students, file)
file.close()

#For searching roll no from binary file


import pickle
file2=open("stud_data.dat","rb")
list_of_students=pickle.load(file2)
roll_no=int(input("Enter roll no of Student to search--"))
found=False
for stud_data in list_of_students:
if(stud_data['roll_no']==roll_no):
found=True
print(stud_data['name'], "found in file.")
if (found==False):
print("No student data found. Pleae try again")

OUTPUT:

5. Create a binary file with roll number, name and marks. Input a roll number and update the marks.
import pickle
file=open("students_data.dat","wb")
dic={}
n=int(input("Enter number of Students::"))
for i in range(n):
roll_no=int(input("Enter Roll No: "))
name=input("Enter Student Name: ")
mark=int(input("Enter Marks: "))
dic[roll_no]={}
dic[roll_no]["Name"]=name
dic[roll_no]["Marks"]=mark
pickle.dump(dic,file)
file.close()
3
#read data from a Binary File
file=open("students_data.dat","rb+")
d=pickle.load(file)
roll_no=int(input("Enter Roll number to update Marks:"))
for i in d:
if i==roll_no:
marks=int(input("Enter the marks: "))
d[i]["Marks"]=marks
print(d)
if(roll_no not in d):
print("Roll Number does not exist. Please try again")
break
pickle.dump(d,file)
file.close()

OUTPUT:

6. Create a CSV file by entering user-id and password, read and search the password for given userid.
#13. Create a CSV file by entering user-id and password, read and search the password for given userid.
import csv
def createlogin():
file= open("login_details.csv", 'w', newline='')
loginwriter=csv.writer(file)
loginwriter.writerow(['username', 'password']) #write header row
while True:
username=input("Enter Username:")
password=input("Enter Password:")
logindetails=[username,password] #Create sequence of user data-python sequence created from
user data
#loginwriter.append(logindetails)
loginwriter.writerow(logindetails) #Python data sequence written on the writer object using
writerow()
ch=input("Enter more (Y/N)?:")
if ch in "nN":
break

print("Data writen in CSV file successfully...")

4
file.close()

#READ DATA FROM CSV FILE


def readlogin():
file= open("login_details.csv", 'r')
print("Reading data from CSV File")
loginreader=csv.reader(file)
for i in loginreader:
print(i)
file.close()
#Searching DATA
def searchlogin():
file= open("login_details.csv", 'r')
print("Searching password with username:")
uname=input("Enter Username to search password:")
found=0
loginreader=csv.reader(file)
for rec in loginreader:
if rec[0]==uname:
print(rec)
found=1
break
if found==0:
print("Sorry...Your record not found")
file.close()
createlogin()
readlogin()
searchlogin()
OUTPUT:

7. Write a program to create a binary file sales.dat and write a menu driven program to do the following:
1. Insert record
2. Search Record
3. Update Record
4. Display record

5
5. Exit
=============================================================================
import pickle
#1.Inserting Records
def insert_rec():
file=open("sales_data.dat","ab")
rec=[]
sales_id=int(input("Enter the Sales ID:"))
name=input("Enter the Produce name:")
price=input("Enter Price of the Product")
rec.append(sales_id)
rec.append(name)
rec.append(price)
pickle.dump(rec,file)
file.close()
#2.Displaying Records
def display_rec():
file=open("sales_data.dat","rb")
print("Records are:")
while True:
try:
data=pickle.load(file)
for i in data:
print(i, end=" ")
print()
except EOFError:
break
file.close()
#3. Searching Records
def search_rec():
file=open("sales_data.dat","rb")
s_id=int(input("Enter the Sales ID you are looking for:"))
while True:
try:
data=pickle.load(file)
if data[0]==s_id: #Searching for record
print(data[0],end="\t")
print(data[1],end="\t")
print(data[2],end="\t")
except EOFError:
break
file.close()
#4. Update Records
def update_rec():
file=open("sales_data.dat","rb")
s_id=int(input("Enter the Sales ID you are looking for:"))
temp=[]
while True:
try:
data=pickle.load(file)
temp.append(data)
except EOFError:
break
file.close()

6
for i in temp:
if i[0]==s_id:
print("Record Found")
new_name=input("Enter the new name:")
i[1]=new_name #shifting name to location 1
file=open("sales_data.dat","wb")
for i in temp:
pickle.dump(i,file)
file.close()
#5.Delete Records
def delete_rec():
file=open("sales_data.dat","rb")
s_id=int(input("Enter the Sales ID you want to delete:"))
temp=[]
while True:
try:
data=pickle.load(file)
temp.append(data)
except EOFError:
break
file.close()
file=open("sales_data.dat","wb")
for i in temp:
if i[0]==s_id:
continue #jump statement----to omit the steps
else:
pickle.dump(i,file)
file.close()
while True:
print("=========================================")
print("MENU DRIVEN PROGRAM FOR SALES MANAGEMENT")
print("==========================================")
print("1. Insert a record")
print("2. Display a record")
print("3. Search a record")
print("4. Update a record")
print("5. Delete a record")
print("6. Exit")
ch=int(input("Enter your choice:"))
if ch==1:
insert_rec()
elif ch==2:
display_rec()
elif ch==3:
search_rec()
elif ch==4:
update_rec()
elif ch==5:
delete_rec()
elif ch==6:
print("Have a nice day!")
exit(0)
else:
print("Invalid Choice:")

7
OUTPUT:

8
8. Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).
import random
'''print("======================================================================")
print("************ROLLIING THE DICE******************************************")
print("======================================================================")'''
#instead of the above code
while True:
print("="*55)
print(" *********************************ROLLING THE DICE*********************")
print("="*55)
num=random.randint(1,6) #used to generate the random numbers integers from lower limit to upper limit
if num==6:
print("Hey.... You got",num,".......")
else:
print("You got",num)
ch=input("Roll again? (Y/N)")
if ch in 'Nn':
break
print("Thanks for Playing!!!!!!!!!!!!!!!!!!!")
OUTPUT:

9. Write a program to read following details of sport’s performance (sport, competitions, prizes-won) of your
school and store into a csv file delimited with tab character.
import csv
9
file=open("sports.csv",'w', newline="")
sports_writer=csv.writer(file, delimiter="\t")
sports_writer.writerow(["SportName", "Competitions", "Prizes"])
ans='y'
i=1
while ans=='y':
print("Record",i)
sport=input("Name of the Sport:")
comp=int(input("Number of the Competitions Participated:"))
prize=int(input("Prizes won:"))
sport_rec=[sport,comp,prize] #creates sequence of user data
sports_writer.writerow(sport_rec)
i=i+1
choice=input("You want to enter more records? (Y/N):")
if choice in "nN":
break
file.close()
OUTPUT:

10. Write a menu driven program to manipulate the bank.csv file.


i. Create a bank account (accno, name, balance)
ii. Display all the account holder details.
iii. Search account holders and total amount in the bank based on account number.
iv. Count the number of account holders and total amount in the bank.
v. Count the number of account holders in the bank.
vi. Updating account Holder's details on the basis of accono.
vii. Deleting the account holder details based on account number. '''
import csv
#1. Create a bank account (accno, name, balance) and Inserting Records
def create_acc():
with open("bank_data.csv","w",newline='') as f1:
acc_writer=csv.writer(f1)
acc_writer.writerow(['Accno','Name','Balance']) #Write header row
rec=[]
while True:
acc_no=int(input("Enter Account Number:"))
name=input("Enter Account Holder's name:")
balance=float(input("Enter Balance amount"))
acc_details=[acc_no,name,balance]
rec.append(acc_details)
ch=input("You want to add another Account (Y/N)??")
if ch in "nN":
10
break
acc_writer.writerows(rec)
print("Account Created.. Data written in CSV file successfully.")
#2.Display all the account holder details.
def display_acc():
with open("bank_data.csv","r") as f2:
print("Reading data from CSV file.. Bank Account details:")
acc_reader=csv.reader(f2)
for i in acc_reader:
print(i)
#3.Search account holders and total amount in the bank based on account number.
def search_acc():
with open("bank_data.csv",'r') as f3:
acc_read=csv.reader(f3)
print("Searching Account holders details:")
acc_no=input("Enter the Account Number to search:")
found=0
for rec in acc_read:
if rec[0]==acc_no:
print("Account Details found")
print("Acc no:", rec[0])
print("Name-", rec[1])
print("Balance-",rec[2])
found =1
break
if found==0:
print("Account not found. Please Try again")
#4. Count the total amount in the bank.
def count_balance():
with open("bank_data.csv","r") as f4:
acc_reader=csv.reader(f4)
columns=next(acc_reader)
balance=0
for rec in acc_reader:
balance+=float(rec[2])
print("The total amount in bank is", balance)
#5. Count the number of account holders in the bank.
def count_acho():
with open("bank_data.csv","r") as f5:
ac_reader=csv.reader(f5)
column=next(ac_reader)
count=0
for rec in ac_reader:
count+=1
print("Number of Account Holders are:", count)
#6.Updating account Holder's details on the basis of accono.
def update_acc():
with open("bank_data.csv","r") as f6:
acc_reader=csv.reader(f6)
print("Updating Account holders details:")
acc_no=input("Enter the Account Number to search:")
found=0
rec=[]
for row in acc_reader:
if row[0]==(acc_no):
name=input("Enter Account Holder's Name to Update:")

11
row[1]=name
balance=float(input("Enter Balance to Update:"))
row[2]=balance
print(row)
found=1
rec.append(row)
if found ==0:
print("Account Holder not found. Please try again")
else:
with open("bank_data.csv","w",newline='') as f7:
acc_writer=csv.writer(f7)
acc_writer.writerows(rec)
f7.seek(0)
acc_reader in acc_reader
for row in acc_reader:
print(row)
print("Account Modified Successfully..")
#7.Deleting the account holder details based on account number.
def delete_acc():
with open("bank_data.csv","r") as f8:
acc_read=csv.reader(f8)
rec=[]
print("Deleting Account holders details:")
acc_no=int(input("Enter the Account Number to search:"))
found=0
for row in acc_read:
if row[0]==str((acc_no)):
found=True
print("Account Deleted")
else:
rec.append(row)
if found==False:
print("Account Number not found.")
else:
with open("bank_data.csv","w+", newline='') as f9: #w+ will erase the data from file
acc_writer=csv.writer(f9)
acc_writer.writerows(rec)
f9.seek(0)
record=csv.reader(f9)
for row in record:
print(row)
while True:
print("=============================================================")
print("*********MENU DRIVEN PROGRAM FOR SALES MANAGEMENT **********")
print("=============================================================")
print("1. Create a bank account (accno, name, balance) and Inserting Records")
print("2. Display all the account holder details.")
print("3. Search and Count the number of account holders and total amount in the bank.")
print("4. Count the number of account holders and total amount in the bank.")
print("5. Count the number of account holders in the bank.")
print("6. Updating account Holder's details on the basis of accono.")
print("7. Deleting the account holder details based on account number. ")
print("8. Exit")
ch=int(input("Enter your choice:"))
if ch==1:
create_acc()

12
elif ch==2:
display_acc()
elif ch==3:
search_acc()
elif ch==4:
count_balance()
elif ch==5:
count_acho()
elif ch==6:
update_acc()
elif ch==7:
delete_acc()
elif ch==8:
print("Have a nice day!")
exit(0)
else:
print("Invalid Choice:")
OUTPUT:

13
14
11. Write a Python program to implement a stack using list.
##Stack inplementation
##stack: implemented as a list
##integer having position of toplost elemnt in stack
def isEmpty(stk):
if stk==[]:
return True
else:
15
return False
def Push(stk,item):
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk):
return "Underflow"
else:
item=stk.pop()
if len(stk)==0:
top=none
else:
top=len(stk)-1
return item
def Peek(stk):
if isEmpty(stk):
return "Under flow"
else:
top=len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("Stack Empty")
else:
top=len(stk)-1
print(stk[top],"<-top")
for a in range(top-1, -1,-1):
print(stk[a])
##Main
stack=[] #Initially stack is empty
top=None
while True:
print("==========STACK OPERATIONS==========")
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4. Display stack")
print("5.Exit")
ch=int(input("Enter your choice(1-5):"))
if ch==1:
item=int(input("Enter item Number:"))
Push(stack,item)
elif ch==2:
item=Pop(stack)
if item=="Underflow:":
print("Underflow! stack is empty!")
else:
print("Popped item is", item)
elif ch==3:
item=Peek(stack)
if item=="Underflow":
print("Underflow! Stack is empty")
else:
print("Topmost item is",item)
elif ch==4:
16
Display(stack)
elif ch==5:
break
else:
print("Invalid Choice!")
OUTPUT:
==========STACK OPERATIONS==========
1.Push
2.Pop
3.Peek
4. Display stack
5.Exit
Enter your choice(1-5):1
Enter item Number:10
==========STACK OPERATIONS==========
1.Push
2.Pop
3.Peek
4. Display stack
5.Exit
Enter your choice(1-5):1
Enter item Number:20
==========STACK OPERATIONS==========
1.Push
2.Pop
3.Peek
4. Display stack
5.Exit
Enter your choice(1-5):1
Enter item Number:30
==========STACK OPERATIONS==========
1.Push
2.Pop
3.Peek
4. Display stack
5.Exit
Enter your choice(1-5):1
Enter item Number:40
==========STACK OPERATIONS==========
1.Push
2.Pop
3.Peek
4. Display stack
5.Exit
Enter your choice(1-5):1
Enter item Number:50
==========STACK OPERATIONS==========
1.Push
2.Pop
3.Peek
4. Display stack
5.Exit
Enter your choice(1-5):4
50 <-top
40
30

17
20
10
==========STACK OPERATIONS==========
1.Push
2.Pop
3.Peek
4. Display stack
5.Exit
Enter your choice(1-5):3
Topmost item is 50
==========STACK OPERATIONS==========
1.Push
2.Pop
3.Peek
4. Display stack
5.Exit
Enter your choice(1-5):2
Popped item is 50
==========STACK OPERATIONS==========
1.Push
2.Pop
3.Peek
4. Display stack
5.Exit
Enter your choice(1-5):4
40 <-top
30
20
10
==========STACK OPERATIONS==========
1.Push
2.Pop
3.Peek
4. Display stack
5.Exit

12. Julie has created a dictionary containing names and marks as key value pairs of 6 students. Write a program,
with separate user defined functions to perform the following operations:

● Push the keys (name of the student) of the dictionary into a stack, where the corresponding value
(marks) is greater than 75.
● Pop and display the content of the stack. For example:
If the sample content of the dictionary is as follows:
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}

The output from the program should be:


TOM ANU BOB OM
CODE:

18
13. Alam has a list containing 10 integers. You need to help him create a program with separate user defined
functions to perform the following operations based on this list.

● Traverse the content of the list and push the even numbers into a stack.
● Pop and display the content of the stack.

For Example:
If the sample Content of the list is as follows:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]

Sample Output of the code should be:


38 22 98 56 34 12
CODE:

14. Write a Python program to write push(book) and pop(book) to add books and remove books from list.
CODE:
def isEmpty(stk):
if stk == []:
return True
else:
return False

def push(stk,item):
stk.append(item)
top = len(stk)-1

def pop(stk):
19
if(stk==[]):
print("Stack empty;UNderflow")
else:
print("Deleted Book is :",stk.pop())

def display(stk):
if isEmpty(stk):
print("Stack empty ")
else :
top = len(stk)-1
print(stk[top],"<-top")
for a in range(top-1,-1,-1):
print(stk[a])
stack=[]
top = None

while True:
print("STACK OPERATION:")
print("1.ADD BOOK")
print("2.Display STACK")
print("3.REMOVE BOOK")
print("4.Exit")
ch = int(input("Enter your choice(1-4):"))
if ch==1:
bno = int(input("Enter BOOK No to be inserted :"))
bname = input("Enter BOOK Name to be inserted :")
item = [bno,bname]
push(stack,item)
input()
elif ch==2:
display(stack)
input()
elif ch==3:
pop(stack)
input()
elif ch==4:
break
else:
print("Invalid choice ")
Output:
>>>
STACK OPERATION:
1.ADD BOOK
2.Display STACK
3.REMOVE BOOK
4.Exit
Enter your choice(1-4):1
Enter BOOK No to be inserted :1
Enter BOOK Name to be inserted :LEARN PYTHON WITH 200 PROGRAMS
STACK OPERATION:
1.ADD BOOK
2.Display STACK
3.REMOVE BOOK
4.Exit
Enter your choice(1-4):1
Enter BOOK No to be inserted :2

20
Enter BOOK Name to be inserted :LET US PYTHON
STACK OPERATION:
1.ADD BOOK
2.Display STACK
3.REMOVE BOOK
4.Exit
Enter your choice(1-4):2
[2, 'LET US PYTHON'] <-top
[1, 'LEARN PYTHON WITH 200 PROGRAMS']
STACK OPERATION:
1.ADD BOOK
2.Display STACK
3.REMOVE BOOK
4.Exit
Enter your choice(1-4):3
Deleted Book is : [2, 'LET US PYTHON']
STACK OPERATION:
1.ADD BOOK
2.Display STACK
3.REMOVE BOOK
4.Exit
Enter your choice(1-4):2
[1, 'LEARN PYTHON WITH 200 PROGRAMS'] <-top
STACK OPERATION:
1.ADD BOOK
2.Display STACK
3.REMOVE BOOK
4.Exit
Enter your choice (1-4):4

15. Each node of stack contains city-details(pin code of city,name of city).Write a python program to implement
push and pop operations in stack.
CODE:
def isEmpty(stk):
if stk == []:
return True
else:
return False
def push(stk,item):
stk.append(item)
top = len(stk)-1
def pop(stk):
if(stk==[]):
print("Stack empty;UNderflow")
else:
print("Deleted City is :",stk.pop())

stack=[]
top = None
while True:
print("STACK OPERATION:")
print("1.ADD City")
print("2.REMOVE City")
print("3.Exit")
ch = int(input("Enter your choice(1-3):"))
if ch==1:

21
pincode = int(input("Enter Pin Code of a city to be inserted :"))
cname = input("Enter City Name to be inserted :")
item = [pincode,cname]
push(stack,item)

input()
elif ch==2:
pop(stack)
input()
elif ch==3:
break
else:
print("Invalid choice ")
input()

Output
STACK OPERATION:
1.ADD City
2.REMOVE City
3.Exit
Enter your choice(1-3):1
Enter Pin Code of a city to be inserted :440027
Enter City Name to be inserted :Nagpur
STACK OPERATION:
1.ADD City
2.REMOVE City
3.Exit
Enter your choice(1-3):2
Deleted City is : [440027, 'Nagpur']
STACK OPERATION:
1.ADD City
2.REMOVE City
3.Exit
Enter your choice(1-3):3

16. Write a program push Employee detail as given below on a Stack. Display the content of stack after push.
1. Employee Number integer
2. Employee Name string
3. Age integer
CODE:
emp=[]
def push(): #Function to push
eno=int(input("Employee Number:"))
ename=input("Employee Name:")
age=int(input("Age:"))
salary=float(input("Salary:"))
e=(eno,ename,age,salary) #create a tuple
emp.append(e)
more='y'
while more in 'Yy':
push() #function call
more=input("Do you want to continue?(y/n):")
print("Employee details in stack")
for i in range(len(emp)-1,-1,-1): #last in first out
print(emp[i])
OUTPUT:

22
17. SET-1
Consider the following Teacher table and write the SQL queries based on it.
1. Create a database School.
2. Display all the databases
3. Use the database School.
4. Create a table Teacher with the following Structure:
Tno Int Primary key
Name Varchar(15) not null
Dob Date
Salary float
Deptno int
1. Display the structure of the table Teacher.
2. Insert 5 records into Teacher table.
3. Display all the records in table Teacher.
QUERIES:
1. Create database school;

2. Display all the databases;

3. Use school;

4. Create table Teacher(Tno int primary key, Name varchar(15) not null, DOB date, salary float, deptno int);

5. Desc teacher;

6. Insert 5 records into Teacher table.

23
7. Display all the records in table Teacher.

18. SET-2
Implement the following SQL commands on the Teacher table:
1. Display the name and date of birth of all the teachers.
2. Display the details of teachers whose salary is between 30000 and 40000 (both values included)
3. Display the names of teachers whose name starts with ‘A’.
4. Display the names and salary of teachers whose salary is greater than 40000.
5. Display the details of teachers whose dob is <’1980-01-01’.
QUERIES:
1. Select name, dob from Teacher;

2. Select * from Teacher where salary between 30000 and 60000;

3. select name from Teacher where Name like ‘A%’;

4. select Name, salary from Teacher where salary>50000;

5. select * from Teacher where DOB<’1980-01-01’;

19. SET-3
24
1. create a table Dept with the following structure:
Deptno int Primary key
Dname varchar(15) not null
2. Display all the tables in database school.
3. Insert 3 records into Dept table.
4. Display all the records in the table Dept.
5. Display the details of all the teachers whose department is ‘science’ from tables Teacher and Dept. (using
natural join)
6. Display the details of all the teachers whose department is ‘maths’ from tables Teacher and Dept. (using Equi
join)
QUERIES:
1. create table dept(Deptno int primary key, Dname varchar(15) not null);

2. show tables;

3. insert into dept values(10,'Science'),(20, 'Maths'), (30, 'IT'),(40,'Social');

4. select * from dept;

5. select * from Teacher natural join dept where Dname="science";

6. select Tno,Name,DOB,Salary,Dname,T.Deptno from Teacher T, dept d where T.Deptno=d.Deptno and


Dname='Maths';

20. SET-4
Implement the following SQL commands on the Teacher table:
1. Increment the salaries of all the teachers by 2000.
2. Display the content of the table Teacher.
3. Add an attribute designation to table Teacher.
4. Display the structure of the table Teacher.
5. Update the designation of all the teachers as ‘PGT’ whose salary is >=50000.
6. Display the records of all the teachers whose designation column is null.
7. Delete the attribute designation.

25
8. Delete the records of teachers whose deptno is 10.
9. Display the table content after deletion.
10. Delete the table Teacher.
QUERIES:
1. update teacher set salary=salary+2000;

2. select * from teacher;

3. alter table teacher add(designation varchar(15));

4. desc teacher;

5. update teacher set designation='PGT' where salary>50000;

6. select * from teacher where designation is null;

7. alter table teacher drop designation;

8. delete from teacher where deptno=10;

9. select * from teacher;

26
10. drop table teacher;

21. SET-5
1. Create a table student with the following structure and insert data:
Roll No Int primary key
Name Varchar(15)
Gender Char(1)
Marks float
2. Display the details of all the students.
3. Display the Total marks of all the students.
4. Display total number of students.
5. Display minimum and maximum marks of students.
6. Display the number of male and female students.
7. Display the details of students in ascending order of their name.
8. Display the details of students in descending order of their marks.
QUERIES:
1. create table student(rollno int primary key, name varchar(15), gender char(1), marks float);

insert into student values(1, 'Arun', 'M',90),(2, 'Deepa', 'F',92.5),(3,'Pranav', 'M',85.5),(4,'Suma', 'F',65),(5,'Teena',
'F',72);

2. select * from student;

3. select sum(marks) 'total' from student;

4. select count(*) 'No: of students' from student;

27
5. select min(marks), max(marks) from student;

6. select gender,count(*) from student group by gender;

7. select * from student order by name;

8. select * from student order by marks desc;

22. Python – MySQL interface


Write a MySQL connectivity program in Python to
• Create a database EMP.
• Create a table employee with the specifications -
EMPNO integer, EMPNAME character (10) in MySQL and perform the following operations:
• Insert two records in it
• Display the contents of the table
#Function to create Database as per users choice
import mysql.connector as ms
def create_database():
try:
dn=input("Enter Database Name=")
c.execute("create database {}".format(dn))
c.execute("use {}".format(dn))
print("Database created successfully")

28
except Exception as a:
print("Database Error",a)
#Function to Drop Database as per users choice
def drop_database():
try:
dn=input("Enter Database Name to be dropped=")
c.execute("drop database {}".format(dn))
print("Database deleted sucessfully")
except Exception as a:
print("Database Drop Error",a)
#Function to create Table
def create_table():
try:
c.execute('''create table employee (empno int(3), empname varchar(20));''')
print("Table created successfully")
except Exception as a:
print("Create Table Error",a)
#Function to Insert Data
def insert_data():
try:
while True:
eno=int(input("Enter employee rollno="))
ename=input("Enter employee name=")
c.execute("use {}".format('EMP'))
c.execute("insert into employee values({},'{}');".format(eno,ename))
db.commit()
choice=input("Do you want to add more record<y/n>=")
if choice in "Nn":
break
except Exception as a:
print("Insert Record Error",a)
#Function to Display Data
def delete_data():
try:
c.execute("select * from employee")
data=c.fetchall()
for i in data:
print(i)
except Exception as a:
print("Display Record Error",a)
db=ms.connect(host="localhost",user="root",password="jss")
c=db.cursor()
while True:
print("MENU\n1. Create Database\n2. Drop Database \n3. Create Table\n4. Insert Record \n5. Display Entire
Data\n6. Exit")
choice=int(input("Enter your choice<1-6>="))
if choice==1:
create_database()
elif choice==2:
drop_database()
elif choice==3:
create_table()
elif choice==4:
insert_data()

29
elif choice==5:
delete_data()
elif choice==6:
break
else:
print("Wrong option selected")

OUTPUT:

23. Create a menu driven program on ‘stock_details’ through MySQL-Python connectivity.


Create table stock_details with the specifications -
stno Integer(3) not null and Primary key, stkname varchar(20), price float, city varchar(15)
import mysql.connector as ms
db=ms.connect(host="localhost",user="root",password="root",database="Employee_details")
cn=db.cursor()
#Function to create Table
def create_stock():
try:
cn.execute('''create table stock_details(stno int(3) not null, stkname varchar(20), price float, city varchar(15),
primary key(stno));''')
print("Table created successfully")

except Exception as a:
print("Create Table Error",a)
#Function to insert records into stock_details
def insert_stock():
while True:
stkno=int(input("Enter stock number:"))
stkname=input("Enter stock name:")
price=float(input("Enter price:"))

30
city=input("Enter city:")
cn.execute("insert into stock_details values({},'{}',{},'{}')".format(stkno,stkname,price,city))
db.commit()
ch=input("Want more records? Press (N/n) to stop entry:")
if ch in 'Nn':
break
#Function to update stock_details
def update_stock():
stkno=int(input("Enter stock number to update:"))
price=float(input("Enter price:"))
cn.execute("update stock_details set price={} where stno={}".format(price,stkno))
print("Selected Stock record updated successfully..")
db.commit()
#Function to delete stock_details
def delete_stock():
try:
stkno=int(input("Enter stock Number to delete:"))
cn.execute("delete from stock_details where stno={}".format(stkno))
print("Selected Stock record deleted..")
db.commit()
except Exception as e:
print("Error",e)
#Function to view stock_details
def view_stock():
cn.execute("select * from stock_details;")
rec=cn.fetchall()
for i in rec:
print(i)
while True:
print("MENU\n1. Create Stock\n2. Insert stock\n3. Update stock \n4. Delete stock\n5. Display stock \n6. Exit")
ch=int(input("Enter your choice<1-6>="))
if ch==1:
create_stock()
if ch==2:
insert_stock()
elif ch==3:
update_stock()
elif ch==4:
delete_stock()
elif ch==5:
view_stock()
elif ch==6:
break
else:
print("Wrong option selected")
OUTPUT:

31
32
24. Write a python program that display first 8 rows fetched from student table of MySQl database student_dbl.
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="suni13",database="student")
if con.is_connected():
print("Connection Successful....")
cur=con.cursor()
cur.execute("Select * from student")
data=cur.fetchmany(8)
for i in data:
print(i)
print("Total rows retreived=",cur.rowcount)

OUTPUT:

33

You might also like