You are on page 1of 62

J.

D TYTLER SCHOOL

BATCH 2022-2023

COMPUTER SCIENCE
PRACTICAL
NAME – KAUSHI NEGI
CLASS – XII – C
BOARD ROLL NO – 26601821
INDEX
S.NO PARTICULARS
1 IMPLEMENTING A STACK CONTAINING NUMBER
2 IMPLEMENTING A STACK CONTAINING NAME OF PERSON AND
SALARY
PROGRAM THAT WILL STORE NAME AND MARKS OF N STUDENTS IN
A DICTIONARYAND THEN PUSH THOSE STUDENTS IN A STACK
WHOSE MARKS ARE GREATER THAN 75.PROGRAM THEN POP THE
3 NAME FROM STACK AND DISPLAY
4 STORE NAME ,CLASS AND MARKS OF DIFFERENT STUDENTS IN A
CSV FILE AND THEN DISPLAY ALL THE RECORDS
PROGRAM TO STORE ROLL NUMBER,NAME,AND MARKS OF STUDENT
IN A BINARY FILE AND DISPLAY THE RECORDS.PROGRAM ALSO
5 SEARCH A PARTICULAR RECORD
MENU DRIVEN PROGRAM TO STORE ROLL NUMBER ,NAME AND
MARKS OF STUDENTS IN A BINARY FILE,DISPLAY ALL RECORDS AND
6 DELETE THE RECORD AND DELETE THE RECORD OF A STUDENT
MENU DRIVEN PROGRAM TO STORE ROLLNO, NAME & MARKS OF
DIFFERENT STUDENTS IN A BINARY FILE , DISPLAY ALL RECORDS
7 AND MODIFY RECORD OF A STUDENT
PYTHON CODE FOR CREATING AND DISPLAY A TEXT FILE.PROGRAM
ALSO COUNT THE NUMBER OF VOWELS AS PER USER'S
8 CHOICE
PYTHON CODE FOR CREATING AND DISPLAY A TEXT FILE.PROGRAM
ALSO COUNT THE NUMBER OF TIMES A WORD 'MY' APPEAR
9 AS PER USER'S CHOICE
PYTHON CODE FOR CREATING AND DISPLAY A TEXT FILE.PROGRAM
ALSO COUNT THE NUMBER OF LINES STARTING WITH ALPHABETS 'A'
10 OR 'a' AS PER USER'S CHOICE
11 PYTHON CODE TO ADD, DISPLAY AND DELETE RECORD OF A
CUSTOMER USING MYSQL AS BACKEND
12 PYTHON CODE TO ADD, DISPLAY AND SEARCH RECORD OF A
CUSTOMER USING MYSQL AS BACKEND
13 SQL
PROGRAM NO. : 1
# implementing a stack containing number
#-------------------------------------------------------------------------
def Push(stk):
num = int(input("Enter a number to be pushed : "))
stk.append(num)
#-------------------------------------------------------------------------

def Pop(stk):
# check for empty stack
if stk == [] :
print("Stack is empty")
else :
num = stk.pop()
print(num , " is popped from stack ")
#-------------------------------------------------------------------
def displaystk(stk):
print("\nContents of stack are : \n")
L = len(stk)
for i in range(L-1, -1, -1) :
print(stk[i], end = ",")
#---------------------------------------------------------------------
def menu():
print("\t\t\t Main Menu \n")
print("Press 1 : To Push an element")
print("Press 2 : To Pop an element")
print("Press 3 : To Display the stack")
print("Press 4 : To Exit")
#--------------------------------------------------------------------
def main(stk) :
while True :
menu()
ch = int(input("\t\tEnter your choice : "))
if ch == 1:
Push(stk)
elif ch == 2 :
Pop(stk)
elif ch == 3 :
displaystk(stk)
elif ch == 4 :
print("\n Good Bye !!!!")
break
else :
print("Invalid Choice !!! ")

#------------------------ top level------------------------------------------------------------


stk1 = [] # actual stack
main(stk1)

#--------------------------------------OUTPUT -----------------------------------------------
Main Menu

Press 1 : To Push an element


Press 2 : To Pop an element
Press 3 : To Display the stack
Press 4 : To Exit
Enter your choice : 1
Enter a number to be pushed : 43
Main Menu

Press 1 : To Push an element


Press 2 : To Pop an element
Press 3 : To Display the stack
Press 4 : To Exit
Enter your choice : 1
Enter a number to be pushed : 34
Main Menu

Press 1 : To Push an element


Press 2 : To Pop an element
Press 3 : To Display the stack
Press 4 : To Exit
Enter yout choice : 2
34 is popped from stack
Main Menu

Press 1 : To Push an element


Press 2 : To Pop an element
Press 3 : To Display the stack
Press 4 : To Exit
Enter your choice : 3

Contents of stack are :

43, Main Menu

Press 1 : To Push an element


Press 2 : To Pop an element
Press 3 : To Display the stack
Press 4 : To Exit
Enter your choice : 1
Enter a number to be pushed : 23
Main Menu

Press 1 : To Push an element


Press 2 : To Pop an element
Press 3 : To Display the stack
Press 4 : To Exit
Enter your choice : 3

Contents of stack are :

23,43, Main Menu

Press 1 : To Push an element


Press 2 : To Pop an element
Press 3 : To Display the stack
Press 4 : To Exit
Enter yout choice : 4

Good Bye !!!!


# PROGRAM NO: 2
# implementing a stack containing Name of Person and Salary
#-------------------------------------------------------------------------------------
def Push(stk):
nm = input("Enter Name : ")
sal = float(input("Enter Salary :
")) rec = [nm, sal] stk.append(rec)

#---------------------------------------------------------------------------------------
def Pop(stk):
# check for empty stack
if stk == [] :
print("Stack is empty")
else :
rec = stk.pop()
print(rec[0] , " is popped from stack ")
#-----------------------------------------------------------------------------------------
def displaystk(stk):
print("\nContents of stack are : \n")
L = len(stk)
for i in range(L-1, -1, -1) :
print(stk[i][0], stk[i][1], sep = '\t')
#-------------------------------------------------------------------------------------
def menu():
print("\t\t\t Main Menu \n")
print("Press 1 : To Push an element")
print("Press 2 : To Pop an element")
print("Press 3 : To Display the stack")
print("Press 4 : To Exit")
#---------------------------------------------------------------------------------
def main(stk) :
while True :
menu()
ch = int(input("Enter your choice : "))
if ch == 1:
Push(stk)
elif ch == 2 :
Pop(stk)
elif ch == 3 :
displaystk(stk)
elif ch == 4 :
print("\n Good Bye !!!!")
break
else :
print("Invalid Choice !!! ")

#------------------------ top level----------


stk1 = [] # actual stack
main(stk1)

#----------------------------------------------OUTUT--------------------------------------------------------------------------
Main Menu

Press 1 : To Push an element


Press 2 : To Pop an element
Press 3 : To Display the stack
Press 4 : To Exit
Enter your choice : 1
Enter Name : Manish
Enter Salary : 4000
Main Menu

Press 1 : To Push an element


Press 2 : To Pop an element
Press 3 : To Display the stack
Press 4 : To Exit
Enter your choice : 1
Enter Name : Jugal
Enter Salary : 7000
Main Menu

Press 1 : To Push an element


Press 2 : To Pop an element
Press 3 : To Display the stack
Press 4 : To Exit
Enter your choice : 3

Contents of stack are :

Jugal 7000.0
Manish 4000.0
Main Menu

Press 1 : To Push an element


Press 2 : To Pop an element
Press 3 : To Display the stack
Press 4 : To Exit
Enter your choice : 2
Jugal is popped from stack
Main Menu

Press 1 : To Push an element


Press 2 : To Pop an element
Press 3 : To Display the stack
Press 4 : To Exit
Enter your choice : 3

Contents of stack are :

Manish 4000.0
Main Menu

Press 1 : To Push an element


Press 2 : To Pop an element
Press 3 : To Display the stack
Press 4 : To Exit
Enter your choice : 4

Good Bye !!!!


“””
PROGRAM NO. 3 :
PROGRAM THAT WILL STORE NAME AND MARKS OF 'N' STUDENTS IN A DICTIONARY
AND THEN PUSH TNAME OF THOSE STUDENTS IN A STACK WHOSE MARKS ARE
GREATER THAN 75. PROGRAM THEN POP THE NAME FROM STACK AND DISPLAY.
"""
#-----------------------------------------------------------------------------------------------------------------
def create_dictionary():
records = dict() # empty dictionary
N = int(input("Enter Number of students : "))
for i in range (N):
nm = input("Enter Name : ")
m = float(input("Enter Marks : "))
records[nm] = m # ADDING AN ELEMENT IN A DICTIONARY
return(records)

#-------------------------------------------------

def push(records, stk):


for name in records :
if records[name] > 75 :
stk.append(name)
#--------------------------------------------------
def display_stack(stk):
print("Name of students scoring greater than 75 : \n")
while stk :
nm = stk.pop()
print(nm)
#-------------------------------------------------------

def menu():
print("\t\t\t Main Menu \n")
print("Press 1 : To add records in a dictionary")
print("Press 2 : To Push the name into stack")
print("Press 3 : To Display the stack")
print("Press 4 : To Exit")

#-------------------------------------------------------
def main(stk) :
while True :
menu()
ch = int(input("Enter yout choice : "))
if ch == 1:
records = create_dictionary()
elif ch == 2 :
push(records,stk)
elif ch == 3 :
display_stack(stk)
elif ch == 4 :
print("\n Good Bye !!!!")
break
else :
print("Invalid Choice !!! ")

#------------------------ top level----------


stk1 = [] # global variable
main(stk1)

#------------------------------------OUTPUT------------------------------------------------------------
Main Menu

Press 1 : To add records in a dictionary


Press 2 : To Push the name into stack
Press 3 : To Display the stack
Press 4 : To Exit

Enter yout choice : 1

Enter Number of students : 4


Enter Name : manish
Enter Marks : 90
Enter Name : jugal
Enter Marks : 56
Enter Name : uma
Enter Marks : 97
Enter Name : kishore
Enter Marks : 23

Main Menu
Press 1 : To add records in a dictionary
Press 2 : To Push the name into stack
Press 3 : To Display the stack
Press 4 : To Exit
Enter your choice : 2
Main Menu

Press 1 : To add records in a dictionary


Press 2 : To Push the name into stack
Press 3 : To Display the stack
Press 4 : To Exit
Enter your choice : 3

Name of students scoring greater than 75 :

uma
manish

Main Menu

Press 1 : To add records in a dictionary


Press 2 : To Push the name into stack
Press 3 : To Display the stack
Press 4 : To Exit
Enter yout choice : 4

Good Bye !!!!


“””
PROGRAM NO. : 4
Aim : Store Name, Class and Marks of different students
in a CSV file and then display all the records
“””
import csv
#--------------------------------------------------------
def createcsv():
f = open("marks.csv", "w", newline = '')
csv_w = csv.writer(f,delimiter = ',')
fields = ['Name', "class", "Marks"]
csv_w.writerow(fields)
records = list()
while True :
nm = input ("Enter Name : ")
cl = input("Enter Class : ")
M = float(input("Enter Marks : "))
rec = [nm, cl, M]
records.append(rec)
ch = input("Wish to write more records (Y/N) : ")
if ch in 'nN' :
break
csv_w.writerows(records)
f.close()
print("File Created")

#---------------------------------------------------------
def readcsv():
f = open("marks.csv", "r", newline ='')
records = csv.reader(f)
for r in records :
print(','.join(r))
f.close()

#------ main----------------
createcsv()
readcsv()
#----------------------------------OUTPUT -----------------------------------------------------
Enter Name : Yogesh
Enter Class : 12
Enter Marks : 89
Wish to write more records (Y/N) : y
Enter Name : Tarun
Enter Class : 12
Enter Marks : 90
Wish to write more records (Y/N) : n
File Created

Name,class,Marks
Yogesh,12,89.0
Tarun,12,90.0
“””
PROGRAM NO. : 5
Program to store Roll Number, Name and Marks of Students in a binary file
and display the records. Program Also search a particular record.
“””
import pickle
#-------------------------------------------------------------
def creatbinary():
file = open("Marks.dat", "wb")
Records = []
while True :
R = int(input("Enter The Roll Numbers :"))
Nm = input("Enter Name :")
M = float(input("Enter Marks : "))
rec = [R,Nm, M]
Records.append(rec)
ch = input("Wish to enter More Records (Y/N): ")
if ch == 'N' or ch == 'n' :
break
pickle.dump(Records,file)
file.close()
#-------------------------------------------------------------
def readbinaryfile():
file = open("Marks.dat", 'rb')
try :
while True :
Records = pickle.load(file)
for rec in Records :
print(rec[0], rec[1], rec[2], sep = '\t')
except EOFError :
pass
file.close()
#-------------------------------------------------------------
def Searchrec():
rn = int(input("\n\n\t\tEnter the roll number : "))
file = open("Marks.dat", 'rb')
try :
while True :
Records = pickle.load(file)
found = False
for rec in Records :
if rec[0] == rn :
found = True
print("Name : ", rec[1])
print("Marks :" , rec[2])
break
if found == False:
print("Record Does not Exist")

except EOFError :
pass
file.close()

# ---------main menu -------------------------------------


def menu(): print("\t\t\t\tMAIN MENU \n\n")
print("\t\t\tPress 1 : To Add Records ")
print("\t\t\tPress 2 : To Display All
Records") print("\t\t\tPress 3 : To Search a
Record") print("\t\t\tPress 4: To Exit")

#-------------main -------------------------------------------
def main():
while True :
menu()
opt = int(input("Enter Your Option : "))
if opt == 1 :
creatbinary()
elif opt == 2 :
readbinaryfile()
elif opt == 3 :
Searchrec()
elif opt == 4 :
break
else :
print("\n\n\t\t Invalid Choice")
#---------------------------------------------------------------
main()
#-------------------------OUTPUT-----------------------------------------------------------------
MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Search a Record
Press 4: To Exit

Enter Your Option : 1

Enter The Roll Numbers :12


Enter Name :Naman
Enter Marks : 55
Wish to enter More Records (Y/N): y
Enter The Roll Numbers :13
Enter Name :Kunal
Enter Marks : 76
Wish to enter More Records (Y/N): n

MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Search a Record
Press 4: To Exit
Enter Your Option : 2
12 Naman 55.0
13 Kunal 76.0

MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Search a Record
Press 4: To Exit
Enter Your Option : 3

Enter the roll number : 12


Name : Naman
Marks : 55.0
MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Search a Record
Press 4: To Exit
Enter Your Option : 4
“””
PROGRAM NO. :6
Menu Driven program to store Roll Number, Name and Marks of Students
in a binary file, Display all records and delete the record of a student.

“””
import pickle
#-------------------------------------------------------------
def creatbinary():
file = open("Marks.dat", "wb")
Records = []
while True :
R = int(input("Enter The Roll Numbers :"))
Nm = input("Enter Name :")
M = float(input("Enter Marks : "))
rec = [R,Nm, M]
Records.append(rec)
ch = input("Wish to enter More Records (Y/N): ")
if ch == 'N' or ch == 'n' :
break
pickle.dump(Records,file)
file.close()
#-------------------------------------------------------------
def readbinaryfile():
file = open("Marks.dat", 'rb')
try :
while True :
Records = pickle.load(file)
for rec in Records :
print(rec[0], rec[1], rec[2], sep = '\t')
except EOFError :
pass
file.close()
#-------------------------------------------------------------
def Deleterec():
rn = int(input("\n\n\t\tEnter the roll number : "))
file = open("Marks.dat", 'rb')
Newrecords = []
try :
while True :
Records = pickle.load(file)
found = False
for rec in Records :
if rec[0] == rn :
found = True
else:
Newrecords.append(rec)
except EOFError :
file.close()
if found == False:
print("Record Does not Exist")
else:
file = open("Marks.dat", 'wb')
pickle.dump(Newrecords, file)
print("Record is deleted successfully")
file.close()

# ---------main menu -------------------------------------


def menu(): print("\t\t\t\tMAIN MENU \n\n")
print("\t\t\tPress 1 : To Add Records ")
print("\t\t\tPress 2 : To Display All
Records") print("\t\t\tPress 3 : To Delete a
Record") print("\t\t\tPress 4: To Exit")

#-------------main -------------------------------------------
def main():
while True :
menu()
opt = int(input("Enter Your Option : "))
if opt == 1 :
creatbinary()
elif opt == 2 :
readbinaryfile()
elif opt == 3 :
Deleterec()
elif opt == 4 :
break
else :
print("\n\n\t\t Invalid Choice")

#---------------------------------------------------------------
main()
#-----------------------------OUTPUT -------------------------------------------------------
MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Delete a Record
Press 4: To Exit
Enter Your Option : 1
Enter The Roll Numbers :12
Enter Name :NAMAN ARORA
Enter Marks : 59
Wish to enter More Records (Y/N): Y
Enter The Roll Numbers :14
Enter Name :KISHORE AHUJA
Enter Marks : 89
Wish to enter More Records (Y/N): N
MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Delete a Record
Press 4: To Exit
Enter Your Option : 2
12 NAMAN ARORA 59.0
14 KISHORE AHUJA 89.0

MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Delete a Record
Press 4: To Exit
Enter Your Option : 3

Enter the roll number : 12


Record is deleted successfully
MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Delete a Record
Press 4: To Exit
Enter Your Option : 2
14 KISHORE AHUJA 89.0

MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Delete a Record
Press 4: To Exit
Enter Your Option : 4
“””
PROGRAM NO. : 7
MENU DRIVEN PROGRAM TO STORE ROLLNO, NAME & MARKS OF DIFFERENT
STUDENTS IN A BINARY FILE , DISPLAY ALL RECORDS AND MODIFY RECORD
OF A STUDENT
“””
import pickle
#-------------------------------------------------------------
def creatbinary():
file = open("Marks.dat", "ab")
Records = []
while True :
R = int(input("Enter The Roll Numbers :"))
Nm = input("Enter Name :")
M = float(input("Enter Marks : "))
rec = [R,Nm, M]
Records.append(rec)
ch = input("Wish to enter More Records (Y/N): ")
if ch == 'N' or ch == 'n' :
break
pickle.dump(Records,file)
file.close()
#-------------------------------------------------------------
def readbinaryfile():
file = open("Marks.dat", 'rb')
try :
while True :
Records = pickle.load(file)
for rec in Records :
print(rec[0], rec[1], rec[2], sep = '\t')
except EOFError :
pass
file.close()
#-------------------------------------------------------------
def Modifyrec():
rn = int(input("\n\n\t\tEnter the roll number : "))
file = open("Marks.dat", 'rb')
Newrecords = []
try :
while True :
Records = pickle.load(file)
found = False
for rec in Records :
if rec[0] == rn :
found = True
R = int(input("Enter The Roll Numbers :"))
Nm = input("Enter Name :")
M = float(input("Enter Marks : "))
rec = [R,Nm, M]
Newrecords.append(rec)
except EOFError :
file.close()
if found == False:
print("Record Does not Exist")
else:
file = open("Marks.dat", 'wb')
pickle.dump(Newrecords, file)
print("Record is modified successfully")
file.close()

# ---------main menu -------------------------------------


def menu(): print("\t\t\t\tMAIN MENU \n\n")
print("\t\t\tPress 1 : To Add Records ")
print("\t\t\tPress 2 : To Display All
Records") print("\t\t\tPress 3 : To Modify a
Record") print("\t\t\tPress 4: To Exit")

#-------------main -------------------------------------------
def main():
while True :
menu()
opt = int(input("Enter Your Option : "))
if opt == 1 :
creatbinary()
elif opt == 2 :
readbinaryfile()
elif opt == 3 :
Modifyrec()
elif opt == 4 :
break
else :
print("\n\n\t\t Invalid Choice")
#---------------------------------------------------------------
main()
#---------------------------------OUTPUT------------------------------------------------------------------
MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Modify a Record
Press 4: To Exit
Enter Your Option : 1
Enter The Roll Numbers :17
Enter Name :KISHAN PAL
Enter Marks : 78
Wish to enter More Records (Y/N): N
MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Modify a Record
Press 4: To Exit
Enter Your Option : 2
14 KISHORE AHUJA 89.0
17 KISHAN PAL 78.0
MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Modify a Record
Press 4: To Exit
Enter Your Option : 3

Enter the roll number : 17


Enter The Roll Numbers :17
Enter Name :KISHAN PAL
Enter Marks : 90
Record is modified successfully
MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Modify a Record
Press 4: To Exit
Enter Your Option : 2
14 KISHORE AHUJA 89.0
17 KISHAN PAL 90.0
MAIN MENU

Press 1 : To Add Records


Press 2 : To Display All Records
Press 3 : To Modify a Record
Press 4: To Exit
Enter Your Option : 4
"""
PROGRAM NO. 8
PYTHON CODE FOR CREATING AND DISPLAY A TEXT FILE.
PROGRAM ALSO COUNT THE NUMBER OF VOWELS AS PER USER'S
CHOICE
"""
#------------------------------------------------
def create_text() :
file = open("DIARY.txt", "w")
print("Enter the text (# to stop ) : \n")
while True :
S = input()
if S == '#' :
break
file.write(S)
file.write('\n')
file.close()
#---------------------------------------------
def disp_text():
file = open("DIARY.txt", "r")
text = file.read()
print("\n\nContents of text file : \n")
print(text)
file.close()
#----------------------------------------------
def countvowels() :
file = open("DIARY.TXT", "r")
S = file.read()
print(S)
v=0
for ch in S :
if ch in 'aAeEiIoOuU':
v = v +1
file.close()
print("Number of vowels : ", v )
# ---------main menu -------------------------------------
def menu(): print("\t\t\t\tMAIN MENU
\n\n") print("\t\tPress 1 : To Create a
Text File") print("\t\tPress 2 : To Display
Text File")
print("\t\tPress 3 : To Count Number of vowels in Text File")
print("\t\tPress 4 : To Exit")
#-------------main -------------------------------------------
def main():
while True :
menu()
opt = int(input("\t\tEnter Your Option : "))
if opt == 1 :
create_text()
elif opt == 2 :
disp_text()
elif opt == 3 :
countvowels()
elif opt == 4 :
print("Good Bye!!")
break
else :
print("\n\n\t\t Invalid Choice")
#---------------------------------------------------------------
main()

#--------------------------------- OUTPUT -------------------------------------------------------


MAIN MENU

Press 1 : To Create a Text File


Press 2 : To Display Text File
Press 3 : To Count Number of vowels in Text File
Press 4 : To Exit
Enter Your Option : 1
Enter the text (# to stop ) :

This is a demo text file.


Here we will count the number of
vowels in the text file and display
them.
#
MAIN MENU

Press 1 : To Create a Text File


Press 2 : To Display Text File
Press 3 : To Count Number of vowels in Text File
Press 4 : To Exit
Enter Your Option : 2

Contents of text file :

This is a demo text file.


Here we will count the number of
vowels in the text file and display
them.

MAIN MENU

Press 1 : To Create a Text File


Press 2 : To Display Text File
Press 3 : To Count Number of vowels in Text File
Press 4 : To Exit
Enter Your Option : 3
This is a demo text file.
Here we will count the number of
vowels in the text file and display
them.

Number of vowels : 29
MAIN MENU

Press 1 : To Create a Text File


Press 2 : To Display Text File
Press 3 : To Count Number of vowels in Text File
Press 4 : To Exit
Enter Your Option : 4
Good Bye!!
"""
PROGRAM NO. 9
PYTHON CODE FOR CREATING AND DISPLAY A TEXT FILE.
PROGRAM ALSO COUNT THE NUMBER OF TIMES A WORD 'MY' APPEAR
AS PER USER'S CHOICE
"""
def create_text() :
file = open("DIARY.txt", "w")
print("Enter the text (# to stop ) : \n")
while True :
S = input()
if S == '#' :
break
file.write(S)
file.write('\n')
file.close()
#---------------------------------------------
def disp_text():
file = open("DIARY.txt", "r")
text = file.read()
print("\n\nContents of text file : \n")
print(text)
file.close()
#------------------------------------------------
def countword():
file = open("DIARY.txt", "r")
S = file.read()
words = S.split()
cnt = 0
for w in words :
if w == 'My' or w == 'my' :
cnt = cnt +1
file.close()
print("Number of time 'my' occur ", cnt)

# ---------main menu -------------------------------------


def menu(): print("\t\t\t\tMAIN MENU \n\n")
print("\t\t\tPress 1 : To Create a Text File")
print("\t\t\tPress 2 : To Display Text File")
print("\t\t\tPress 3 : To Count word 'My' in Text
File") print("\t\t\tPress 4 : To Exit")
#-------------main -------------------------------------------
def main():
while True :
menu()
opt = int(input("\t\t\tEnter Your Option : "))
if opt == 1 :
create_text()
elif opt == 2 :
disp_text()
elif opt == 3 :
countword()
elif opt == 4 :
print("Good Bye!!!")
break
else :
print("\n\n\t\t Invalid Choice")
#---------------------------------------------------------------
main()

#-------------------------------------OUTPUT -------------------------------------------------------------------
MAIN MENU

Press 1 : To Create a Text File


Press 2 : To Display Text File
Press 3 : To Count word 'My' in Text File
Press 4 : To Exit
Enter Your Option : 1
Enter the text (# to stop ) :

This is a text file in which


I am writing my experience of
programming. My friends call this
a text file.
#
MAIN MENU

Press 1 : To Create a Text File


Press 2 : To Display Text File
Press 3 : To Count word 'My' in Text File
Press 4 : To Exit
Enter Your Option : 2

Contents of text file :

This is a text file in which


I am writing my experience of
programming. My friends call this
a text file.

MAIN MENU

Press 1 : To Create a Text File


Press 2 : To Display Text File
Press 3 : To Count word 'My' in Text File
Press 4 : To Exit
Enter Your Option : 3
Number of time 'my' occur 2
MAIN MENU

Press 1 : To Create a Text File


Press 2 : To Display Text File
Press 3 : To Count word 'My' in Text File
Press 4 : To Exit
Enter Your Option : 4
Good Bye!!!

"""
PROGRAM NO. 10
PYTHON CODE FOR CREATING AND DISPLAY A TEXT FILE.
PROGRAM ALSO COUNT THE NUMBER OF LINES STARTING WITH
ALPHABETS 'A' OR 'a' AS PER USER'S CHOICE
"""
def create_text() :
file = open("DIARY.txt", "w")
print("Enter the text (# to stop ) : \n")
while True :
S = input()
if S == '#' :
break
file.write(S)
file.write('\n')
file.close()
#---------------------------------------------
def disp_text():
file = open("DIARY.txt", "r")
text = file.read()
print("\n\nContents of text file : \n")
print(text)
file.close()
#----------------------------------------------
def countlines():
file = open("DIARY.txt", "r")
Lines = file.readlines()
cnt = 0
for L in Lines :
if L[0] == 'A' or L[0] == 'a' :
cnt = cnt +1
print("Number of lines starting with 'A' or 'a' = ", cnt)
file.close()

# ---------main menu -------------------------------------


def menu(): print("\t\t\t\tMAIN MENU
\n\n") print("\t\tPress 1 : To Create a
Text File") print("\t\tPress 2 : To Display
Text File")
print("\t\tPress 3 : To Count Number of lines starting with 'A' or 'a'")
print("\t\tPress 4 : To Exit")
#-------------main -------------------------------------------
def main():
while True :
menu()
opt = int(input("\t\tEnter Your Option : "))
if opt == 1 :
create_text()
elif opt == 2 :
disp_text()
elif opt == 3 :
countlines()
elif opt == 4 :
print("Good Bye !!!!")
break
else :
print("\n\n\t\t Invalid Choice")
#---------------------------------------------------------------
main()

#--------------------------------------------------OUTPUT---------------------------------------------------------
MAIN MENU

Press 1 : To Create a Text File


Press 2 : To Display Text File
Press 3 : To Count Number of lines starting with 'A' or 'a'
Press 4 : To Exit
Enter Your Option : 1
Enter the text (# to stop ) :

A test file is a file in which


data is stored in ASCII format.
A human readble file in which each
line is terminated by a new line character.
#
MAIN MENU

Press 1 : To Create a Text File


Press 2 : To Display Text File
Press 3 : To Count Number of lines starting with 'A' or 'a'
Press 4 : To Exit
Enter Your Option : 2
Contents of text file :

A test file is a file in which


data is stored in ASCII format.
A human readble file in which each
line is terminated by a new line character.

MAIN MENU

Press 1 : To Create a Text File


Press 2 : To Display Text File
Press 3 : To Count Number of lines starting with 'A' or 'a'
Press 4 : To Exit
Enter Your Option : 3
Number of lines starting with 'A' or 'a' = 2
MAIN MENU

Press 1 : To Create a Text File


Press 2 : To Display Text File
Press 3 : To Count Number of lines starting with 'A' or 'a'
Press 4 : To Exit
Enter Your Option : 5

Invalid Choice
MAIN MENU

Press 1 : To Create a Text File


Press 2 : To Display Text File
Press 3 : To Count Number of lines starting with 'A' or 'a'
Press 4 : To Exit
Enter Your Option : 4
Good Bye !!!!
“””
PROGRAM NO. : 11
PYTHON CODE TO ADD, DISPLAY AND DELETE RECORD OF A
CUSTOMER USING MYSQL AS BACKEND
“””
from os import *
import mysql.connector as conn
Dbconn = conn.connect(host = 'localhost', user = 'root',passwd = 'mysql')
Dbcur = Dbconn.cursor()
#----------------------------------------------------------------
def draw_line(ch = '=',n = 100):
for i in range(n):
print(ch, end = '')
print()
#----------------------------------------------------------------
def Customer_menu():
print("\t\t\t\t\tCustomer Management \n\n")
print("\t\t\t Press 1 : To Add new Customer \n")
print("\t\t\t Press 2 : To Delete a Customer \n")
print("\t\t\t Press 4 : To Display the detail of Customer \n ")
print("\t\t\t Press 5 : To Exit ")
#----------------------------------------------------------------
# function : To add a new Customer
#----------------------------------------------------------------
def add_customer():
system("cls")
print("\n\n\t\t\t\tCustomer id : ", end = '')
cid = input()
draw_line()
print("\n\n\t\t\t\tCustomer Name : ", end = '')
cname = input()
draw_line()
print("\n\n\t\t\t\tCustomer Address : ", end = '')
cadd = input()
draw_line()
print("\n\n\t\t\t\tPhone Number : ", end = '')
cphone = int(input())
draw_line()

sql = "insert into Customer (cust_id, Cname, Caddress,phone )\


values ( '{}', '{}','{}', {} )".format(cid,cname,cadd,cphone)
Dbcur.execute(sql)
Dbconn.commit()
print(Dbcur.rowcount, " record is inserted")
print("Press any key to continue........", end ='')
input()

#-------------------------------------------------------------
# function : To delete record of a Customer
#-------------------------------------------------------------
def delete_customer():

bno = input("Enter the cust_id : ")


query = "Delete from Customer where cust_id = %s"
data = (bno,)
Dbcur.execute(query,data)
Dbconn.commit()
print(Dbcur.rowcount, " record is successfully deleted")
print("\n\n\t\t\t Press any key to continue.... ", end = '')
input()

#-------------------------------------------------------------------------
# function to display the Customers Detail
#-------------------------------------------------------------------------
def disp_customer():
system("cls")
print("\n\n")
print('{:^100s}'.format("List of Customers"))
print("\n\n")
sql = "Select * from Customer"
Dbcur.execute(sql)
records = Dbcur.fetchall()
draw_line("=",100)
print('{:^10s} {:^20s} {:^25s} {:^25s}'
.format("CUST_ID" ,"NAME","ADDRESS", "PHONE NUMBER"))
draw_line("=",100)
for rec in records :
print('{:^10s} {:<25s} {:<25s} {:<10d}'
.format(rec[0] ,rec[1], rec[2],rec[3]))
draw_line('_',100)
print("\n\n\t\t\t Press any key to continue.... ", end = '')
input()
#----------------------------------------------------------
def database_setup():
query = "Drop database BOOKSHOP1"
query1 = "Create Database BOOKSHOP1"
query2 = "USE BOOKSHOP1"
query3 = "Create table Customer ( cust_id char(4) Primary Key, CName
varchar(25),\ Caddress varchar(30), phone bigint(10))"

Dbcur.execute(query)
Dbcur.execute(query1)
Dbcur.execute(query2)
Dbcur.execute(query3)
#-----------------------------------------------------------------------------------------------------------------
def Customer_app():
database_setup()
while True :
system("cls")
Customer_menu()
ch = int(input("\n\n\t\t\tEnter your choice : "))
if ch == 1 :
add_customer()
elif ch == 2 :
delete_customer()
elif ch == 3 :
disp_customer()
elif ch == 4:
Dbcur.close()
Dbconn.close()
break
else :
print("Invalid Choice !!!! ")
print("\n\n\t\t\t Press any key to continue.... ", end = '')
input()
#--------------------------------------------------------
Customer_app()
#------------------------------------------------OUTPUT--------------------------------------------------------------------
Customer Management

Press 1 : To Add new Customer


Press 2 : To Delete a Customer
Press 3 : To Display the detail of Customer
Press 4 : To Exit
Enter your choice : 1

Customer id : C104
===========================================================================
Customer Name : JUGAL NATH
===========================================================================
Customer Address : 56 NAI WALA KAROL BAGH
===========================================================================
Phone Number : 6278288289
===========================================================================
1 record is inserted
Press any key to continue........

Customer Management

Press 1 : To Add new Customer


Press 2 : To Delete a Customer
Press 3 : To Display the detail of Customer
Press 4 : To Exit

Enter your choice : 4

List of Customers
====================================================================================
CUST_ID NAME ADDRESS PHONE NUMBER
====================================================================================
C104 JUGAL NATH 56 NAI WALA KAROL BAGH 6278288289
_____________________________________________________________________________________
C105 AMIT KUMAR 56 OLD RAJNDER NAGAR 7828289728
_____________________________________________________________________________________

Press any key to continue....


Customer Management

Press 1 : To Add new Customer


Press 2 : To Delete a Customer
Press 3 : To Display the detail of Customer
Press 4 : To Exit

Enter your choice : 2


Enter the cust_id : C104
1 record is successfully deleted

Press any key to continue....


“””
PROGRAM NO. : 12
PYTHON CODE TO ADD, DISPLAY AND SEARCH RECORD OF A
CUSTOMER USING MYSQL AS BACKEND
“””

from os import *
import mysql.connector as conn
Dbconn = conn.connect(host = 'localhost', user = 'root',passwd = 'mysql')
Dbcur = Dbconn.cursor()
#----------------------------------------------------------------
def draw_line(ch = '=',n = 100):
for i in range(n):
print(ch, end = '')
print()
#----------------------------------------------------------------
def Customer_menu():
print("\t\t\t\t\tCustomer Management \n\n")
print("\t\t\t Press 1 : To Add new Customer \n")
print("\t\t\t Press 2 : To Search a Customer \n")
print("\t\t\t Press 3 : To Display the detail of Customer \n ")
print("\t\t\t Press 4 : To Exit ")
#----------------------------------------------------------------
# function : To add a new Customer
#----------------------------------------------------------------
def add_customer():
system("cls")
print("\n\n\t\t\t\tCustomer id : ", end = '')
cid = input()
draw_line()
print("\n\n\t\t\t\tCustomer Name : ", end = '')
cname = input()
draw_line()
print("\n\n\t\t\t\tCustomer Address : ", end = '')
cadd = input()
draw_line()
print("\n\n\t\t\t\tPhone Number : ", end = '')
cphone = int(input())
draw_line()

sql = "insert into Customer (cust_id, Cname, Caddress,phone )\


values ( '{}', '{}','{}', {} )".format(cid,cname,cadd,cphone)
Dbcur.execute(sql)
Dbconn.commit()
print(Dbcur.rowcount, " record is inserted")
print("Press any key to continue........", end ='')
input()
#---------------------------------------------------------------
# function : To search a customer
#---------------------------------------------------------------
def search_customer():
bn = input("Enter Cust_Id : ")
query = "Select * from Customer where Cust_id = %s"
data = (bn,)
Dbcur.execute(query,data)
records = Dbcur.fetchall()
if records == []:
print("Customer does not Exist")
else :
system("cls")
print("\n\n")
print('{:^100s}'.format("Detail of Customer"))
print("\n\n")
for r in records :
print("\t\t\tCustomer id : ", r[0], end = '\n')
print("\t\t\tCustomer's Name : ", r[1], end = '\n')
print("\t\t\tCustomer's Address : ", r[2], end = '\n')
print("\t\t\tPhone Number : ", r[3], end = '\n')

print("\n\n\t\t\t Press any key to continue.... ", end = '')


input()
#-------------------------------------------------------------------------
# function to display the Customers Detail
#-------------------------------------------------------------------------
def disp_customer():
system("cls")
print("\n\n")
print('{:^100s}'.format("List of Customers"))
print("\n\n")
sql = "Select * from Customer"
Dbcur.execute(sql)
records = Dbcur.fetchall()
draw_line("=",100)
print('{:^10s} {:^20s} {:^25s} {:^25s}'
.format("CUST_ID" ,"NAME","ADDRESS", "PHONE NUMBER"))
draw_line("=",100)
for rec in records :
print('{:^10s} {:<25s} {:<25s} {:<10d}'
.format(rec[0] ,rec[1], rec[2],rec[3]))
draw_line('_',100)
print("\n\n\t\t\t Press any key to continue.... ", end = '')
input()
#----------------------------------------------------------
def database_setup():
query = "Drop database BOOKSHOP1"
query1 = "Create Database BOOKSHOP1"
query2 = "USE BOOKSHOP1"
query3 = "Create table Customer ( cust_id char(4) Primary Key, CName
varchar(25),\ Caddress varchar(30), phone bigint(10))"
Dbcur.execute(query)
Dbcur.execute(query1)
Dbcur.execute(query2)
Dbcur.execute(query3)
#---------------------------------------------------------------
def Customer_app():
database_setup()
while True :
system("cls")
Customer_menu()
ch = int(input("\n\n\t\t\tEnter your choice : "))
if ch == 1 :
add_customer()
elif ch == 2 :
search_customer()
elif ch == 3 :
disp_customer()
elif ch == 4:
Dbcur.close()
Dbconn.close()
break
else :
print("Invalid Choice !!!! ")
print("\n\n\t\t\t Press any key to continue.... ", end = '')
input()
#--------------------------------------------------------
Customer_app()
#-------------------------------------------------OUTPUT------------------------------------
Customer Management

Press 1 : To Add new Customer


Press 2 : To Search a Customer
Press 3 : To Display the detail of Customer
Press 4 : To Exit
Enter your choice : 1

Customer id : C101
=====================================================================================
Customer Name : HIMANSHU
=====================================================================================
Customer Address : 7/10 ROOP NAGAR DELHI
Phone Number : 6726772922
=====================================================================================
1 record is inserted
Press any key to continue........

Customer Management

Press 1 : To Add new Customer


Press 2 : To Search a Customer
Press 3 : To Display the detail of Customer
Press 4 : To Exit
Enter your choice : 3

List of Customers
=====================================================================================
CUST_ID NAME ADDRESS PHONE NUMBER
=====================================================================================
C101 HIMANSHU 7/10 ROOP NAGAR DELHI 6726772922
_____________________________________________________________________________________
C105 AMIT KUMAR 56 OLD RAJNDER NAGAR 7828289728
_________________________________________________________________________________
C106 MANISH KHURANA 16A R-BLOCK NEW RAJINDER NGR 9810086865
____________________________________________________________________________________
Press any key to continue....
Customer Management

Press 1 : To Add new Customer


Press 2 : To Search a Customer
Press 3 : To Display the detail of Customer
Press 4 : To Exit
Enter your choice : 2
Enter Cust_Id : C101

Detail of Customer
Customer id : C101
Customer's Name : HIMANSHU
Customer's Address : 7/10 ROOP NAGAR DELHI
Phone Number : 6726772922

Press any key to continue....


“””
PROGRAM NO. : 13
PYTHON CODE TO ADD, DISPLAY AND MODIFY RECORD OF A CUSTOMER
USING MYSQL AS BACKEND
“””

from os import *
import mysql.connector as conn
Dbconn = conn.connect(host = 'localhost', user = 'root',passwd = 'mysql')
Dbcur = Dbconn.cursor()
#----------------------------------------------------------------
def draw_line(ch = '=',n = 100):
for i in range(n):
print(ch, end = '')
print()
#----------------------------------------------------------------
def Customer_menu():
print("\t\t\t\t\tCustomer Management \n\n")
print("\t\t\t Press 1 : To Add new Customer \n")
print("\t\t\t Press 2 : To Modify a Customer \n")
print("\t\t\t Press 3 : To Display the detail of Customer \n ")
print("\t\t\t Press 4 : To Exit ")
#----------------------------------------------------------------
# function : To add a new Customer
#----------------------------------------------------------------
def add_customer():
system("cls")
print("\n\n\t\t\t\tCustomer id : ", end = '')
cid = input()
draw_line()
print("\n\n\t\t\t\tCustomer Name : ", end = '')
cname = input()
draw_line()
print("\n\n\t\t\t\tCustomer Address : ", end = '')
cadd = input()
draw_line()
print("\n\n\t\t\t\tPhone Number : ", end = '')
cphone = int(input())
draw_line()

sql = "insert into Customer (cust_id, Cname, Caddress,phone )\


values ( '{}', '{}','{}', {} )".format(cid,cname,cadd,cphone)
Dbcur.execute(sql)
Dbconn.commit()
print(Dbcur.rowcount, " record is inserted")
print("Press any key to continue........", end ='')
input()

#---------------------------------------------------------------
# function : To search a customer
#---------------------------------------------------------------
def modify_customer():
bn = input("Enter Cust_Id : ")
query = "Select * from Customer where Cust_id = %s"
data = (bn,)
Dbcur.execute(query,data)
r = Dbcur.fetchone()
if r == []:
print("Customer does not Exist")
else :
system("cls")
print("\n\n")
print('{:^100s}'.format("Detail of Customer"))
print("\n\n")
print("\t\t\tCustomer id : ", r[0], end = '\n')
print("\t\t\tCustomer's Name : ", r[1], end = '\n')
print("\t\t\tCustomer's Address : ", r[2], end = '\n')
print("\t\t\tPhone Number : ", r[3], end = '\n')
opt = input("\n\n\t\t\t Want to modify(Y/N) :")
if opt in 'Yy' :
system("cls")
draw_line()
print("\n\n\t\t\t\tCustomer Name : ", end = '')
cname = input()
draw_line()
print("\n\n\t\t\t\tCustomer Address : ", end = '')
cadd = input()
draw_line()
print("\n\n\t\t\t\tPhone Number : ", end = '')
cphone = int(input())
draw_line()
sql = "UPDATE Customer SET Cname = '{}', Caddress = '{}',\
phone = {} where cust_id = '{}'".format(cname,cadd,cphone,bn)

Dbcur.execute(sql)
Dbconn.commit()
print(Dbcur.rowcount, " record is updated")

print("\n\n\t\t\t Press any key to continue.... ", end = '')


input()
#-------------------------------------------------------------------------
# function to display the Customers Detail
#-------------------------------------------------------------------------
def disp_customer():
system("cls")
print("\n\n")
print('{:^100s}'.format("List of Customers"))
print("\n\n")
sql = "Select * from Customer"
Dbcur.execute(sql)
records = Dbcur.fetchall()
draw_line("=",100)
print('{:^10s} {:^20s} {:^25s} {:^25s}'
.format("CUST_ID" ,"NAME","ADDRESS", "PHONE NUMBER"))
draw_line("=",100)
for rec in records :
print('{:^10s} {:<25s} {:<25s} {:<10d}'
.format(rec[0] ,rec[1], rec[2],rec[3]))
draw_line('_',100)
print("\n\n\t\t\t Press any key to continue.... ", end = '')
input()
#----------------------------------------------------------
def database_setup():

query = "Drop database BOOKSHOP1"


query1 = "Create Database BOOKSHOP1"

query2 = "USE BOOKSHOP1"

query3 = "Create table Customer ( cust_id char(4) Primary Key, CName


varchar(25),\ Caddress varchar(30), phone bigint(10))"
#Dbcur.execute(query)
#Dbcur.execute(query1)
Dbcur.execute(query2)
#Dbcur.execute(query3)

def Customer_app():
database_setup()

while True :
system("cls")
Customer_menu()
ch = int(input("\n\n\t\t\tEnter your choice : "))
if ch == 1 :
add_customer()
elif ch == 2 :
modify_customer()
elif ch == 3 :
disp_customer()
elif ch == 4:
Dbcur.close()
Dbconn.close()
break
else :
print("Invalid Choice !!!! ")
print("\n\n\t\t\t Press any key to continue.... ", end = '')
input()
#--------------------------------------------------------
Customer_app()

#------------------------------------------------------OUTPUT -------------------------------------------------------------
Customer Management

Press 1 : To Add new Customer


Press 2 : To Modify a Customer
Press 3 : To Display the detail of Customer
Press 4 : To Exit

Enter your choice :1


Customer id : C101
=====================================================================================
Customer Name : HIMANSHU
=====================================================================================
Customer Address : 7/10 ROOP NAGAR DELHI
Phone Number : 6726772922
=====================================================================================
1 record is inserted
Press any key to continue........

Customer Management

Press 1 : To Add new Customer


Press 2 : To Modify a Customer
Press 3 : To Display the detail of Customer
Press 4 : To Exit

Enter your choice :3

List of Customers

=====================================================================================
CUST_ID NAME ADDRESS PHONE NUMBER
====================================================================================
C101 HIMANSHU 7/10 ROOP NAGAR DELHI 6726772922
____________________________________________________________________________________
C105 AMIT KUMAR 56 OLD RAJNDER NAGAR 7828289728
____________________________________________________________________________________
C106 JDH DHHJDJ 2788273822
____________________________________________________________________________________
Press any key to continue....

Customer Management

Press 1 : To Add new Customer


Press 2 : To Modify a Customer
Press 3 : To Display the detail of Customer
Press 4 : To Exit

Enter your choice :2


Enter Cust_id : C106
Detail of Customer
Customer id : C106
Customer's Name : JDH
Customer's Address : DHHJDJ
Phone Number : 2788273822

Want to modify(Y/N) :Y

Detail of Customer
================================================================================
Customer Name : MANISH KHURANA
================================================================================
Customer Address : 16 R BLOCK NEW RAJINDER NGR
================================================================================
Phone Number : 9810030678
================================================================================
1 record is updated
Press any key to continue....

Customer Management

Press 1 : To Add new Customer


Press 2 : To Modify a Customer
Press 3 : To Display the detail of Customer
Press 4 : To Exit

Enter your choice :3


List of Customers
====================================================================================
CUST_ID NAME ADDRESS PHONE NUMBER
====================================================================================
C101 HIMANSHU 7/10 ROOP NAGAR DELHI 6726772922
____________________________________________________________________________________
C105 AMIT KUMAR 56 OLD RAJNDER NAGAR 7828289728
____________________________________________________________________________________
C106 MANISH KHURANA 16 R BLOCK NEW RAJINDER NGR 9810030678
____________________________________________________________________________________

Press any key to continue....


Q1. Consider the following tables. Write SQL commands for the
statement(1) to (8).
TABLE : SENDER

SenderID SenderName SenderAddress SenderCity


ND01 R.Jain 2 ABC Appts New Delhi
MU02 H.Sinha 12 NewTown Mumbai
MU15 S Jha 27/A, Park Street Mumbai
ND50 T Prasad 122-K, SDA New Delhi

TABLE : RECIPIENT

RecID SenderID RecName RecAddress RecCity


K005 ND01 R Bajpayee 5 Central Avenue KolKata
ND08 MU02 S Mahajan 116 A vihar New Delhi
MU19 ND01 H Singh 2A Andheri East Mumbai
MU32 MU15 PK Swamy B5 CS Terminus Mumbai
Nd48 Nd50 S Tripathi 13 Mayur Vihar New Delhi

1. Create a database STORE in the system.

2. Create two tables ‘SENDER’ and ‘RECIPIENT’ in the database.

3. Insert the data in the two tables.

4. Display the names of all senders From Mumbai.

5. Display the RecID, SenderName, SenderAddress, RecName, RecAddress for every

Recipient.

6. Display Recipient details in ascending order of Recname.

7. Display the numbers of Receipient from each city.

8. Delete the records of Recipient whose name start with letter ‘S’.
Ans.:
(1) CREATE DATABASE STORE

(2) USE STORE


CREATE TABLE SENDER
(
SenderID VARCHAR(4) PRIMARY KEY,
SenderName VARCHAR(20) NOT
NULL, SenderAddress VARCHAR(30),
SenderCity VARCHAR(10)
);

CREATE TABLE RECIPIENT


(
RecID VARCHAR(4) PRIMARY
KEY, SenderID VARCHAR(4),
RecName VARCHAR(20),
RecAddress VARCHAR(30),
RecCity VARCHAR(10),
FOREIGN KEY SenderID REFERENCES SENDER(SenderID)
);

(3) INSERT INTO SENDER


VALUES(‘ND01’, ‘R.JAIN’, ‘2 ABC Appts’, ‘New Delhi’);

INSERT INTO SENDER


VALUES(‘MU02’, ‘H.SINHA’, ’12 NEW TOWN’, ‘Mumbai’);

INSERT INTO SENDER


VALUES(‘MU15’, ‘S JHA’, ‘27/A PARK STREET’, ‘Mumbai’);

INSERT INTO SENDER


VALUES(‘ND50’, ‘T PRASAD’, ‘122-K SDA’, ‘New Delhi’);
INSERT INTO RECIPIENT
VALUES(‘K005’, ‘ND01’,’R.bAJPAYEE’,’5 CENTRAL Revenue’, ‘Kolkatta’);

INSERT INTO RECIPIENT


VALUES(‘ND08’, ‘MU02’,’S Mahajan’,’116 A Vihar’, ‘New Delhi’);

INSERT INTO RECIPIENT


VALUES(‘MU32’, ‘MU15’,’PK SWAMI’,’B5 CS Terminus’, ‘Mumbai’);

INSERT INTO RECIPIENT


VALUES(‘MU19’, ‘ND01’,’H Singh’,’2A Andheri East’, ‘Mumbai’);

INSERT INTO RECIPIENT


VALUES(‘ND48’, ‘ND50’,’S TRIPATHI’,’13 Mayur Vihar’, ‘New Delhi’);

(4) SELECT SenderName FROM SENDER WHERE SenderCity = “Mumbai”;

(5) SELECT R.RecId, SenderName, SenderAdress, RecName, RecAddress


FROM SENDER S, RECIPIENT R
WHERE S.SenderID = R.SenderID;

(6) SELECT * FROM RECIPIENT ORDER BY RecName;

(7) SELECT RecCity, Count(*)


FROM RECIPENT
GROUP BY RecCITY;

(8) DELETE FROM RECIPIENT WHERE RecName LIKE “S%”;


Q2.Consider the following tables Product and Client. Write SQL commands
for the statements 1 to 5.

TABLE : PRODUCT

P_ID Productname Manufacturer Price


TP01 Telcom Powder LAK 40
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95

TABLE : CLIENT

C_ID ClientName City P_ID


01 Cosmetic Shop Delhi FW05
06 Total health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty Women Delhi FW12
16 Dreams Bangalore TP01

1. Display the details of those clients whose city is Delhi.

2. Display the details of products whose price is in the range of 50 to 100.

3. Display the ClientName, City from table Client and Productname, Price from the

table Product with their corresponding matching P_ID.

4. Increase the price of all products by 10.

5. Insert a new row with suitable data in the table Product.


Ans.

(1) SELECT * FROM CLIENT WHERE CITY = “Delhi”;

(2) SELECT * FROM PRODUCT WHERE PRICE BETWEEN 50 AND 100;

(3) SELECT C.ClientName, C.City, P.ProductName,


P.Price WHERE C.P_ID = P.P_ID;

(4) UPDATE PRODUCT


SET PRICE = PRICE + PRICE *0.10;

(5) INSERT INTO PRODUCT


VALUES ( ‘SH02’, ‘DOVE SHAMPOO’, ‘XYZ’, 200)
Q3.Consider the following tables ITEM and Customer. Write SQL commands for
the statements 1 to 5.

TABLE : ITEM

I_ID Itemname Manufacturer Price


PC01 Personal Computer Lenovo 40000
LC05 Laptop Lenovo 45000
PC03 Personal Computer Apple 55000
PC06 Personal Computer HP 120000
LC03 Laptop HP 95000

TABLE : CUSTOMER

C_ID CustomerName City I_ID


01 N Roy Delhi LC03
06 H Singh Mumbai PC03
12 R Pandey Delhi PC06
15 C Sharma Delhi LC03
16 K Aggarwal Bangalore PC01

1. Display the details of those customers whose city is Delhi.

2. Display the details of ITEMS whose price is in the range of 35000 to 55000.

3. Display the Customer Name, City from table Customer and Item name, Price from

the table ITEM with their corresponding matching I_ID.

4. Increase the price of all products by 1000.

5. Delete the information of those Items which are manufactured by Lenovo.


Ans.

(1) SELECT * FROM CUSTOMER WHERE CITY = “Delhi”;

(2) SELECT * FROM ITEMS WHERE PRICE BETWEEN 35000 AND 55000;

(3) SELECT CustomerName, City, ItemName, Price


FROM CUSTOMER C, ITEM I
WHERE C.I_ID = I.I_ID;

(4) UPDATE ITEM SET PRICE = PRICE + PRICE *0.10;

(5) DELETE FROM ITEM WHERE manufacturer = “Lenovo”;


Q4. Consider the following tables : Consignor and Consignee. Write SQL
commands for the statements (1) to (5).
TABLE : CONSIGNOR

CnorID CnorName CnorAddress City


ND01 R Singhal 24 ANC Enclave New Delhi
MU02 Amit Kumar 123 Plam Enclave Mumbai
MU15 R Kohli 5/A South Street Mumbai
ND05 S Kaur 27-k Westend New Delhi

TABLE : CONSIGNEE

CneeID CnorID CneeName CneeAddress CneeCity


MU05 ND01 Rahul kishore 5 Park avenue KolKata
ND08 ND01 P Dhingra 11/6 Moore Enclave New Delhi
K019 MU15 A P Roy 2A Central Avenue Kolkata
MU32 ND05 S Mittal P245 AB Colony Mumbai
ND48 MU15 B P jain 13 Block A, Mayur Vihar New Delhi

1. Display the names of all Consignors From Mumbai.

2. Display the CneeID, CnorName, CnorAddress, CneeName, CneeAddress for every Consignee.

3. Display Consignee details in ascending order of CneeName.

4. Display the numbers of Consignors from each city.

5. Delete the records of Consignee whose name end with letter ‘e’.

6. Display the structure of CONSIGNEE table.

7. What is the degree and Cardinality of table CONSIGNOR.


Ans.

(1) SELECT Cnorname FROM CONSIGNOR WHERE CITY = ‘Mumbai’;

(2) SELECT C.CneeID, C.CnorName, C.CnorAddress, R.CneeName, R.CneeAddress

FROM CONCIGNOR C, CONSIGNEE


R WHERE C.CnorId = R.CnorID;

(3) SELECT * FROM CONSIGNEE ORDER BY CneeName;

(4) SELECT CITY, COUNT(*) FROM CONSIGNOR GROUP BY CITY;

(5) DELETE FROM CONSIGNEE WHERE CneeName LIKE “%e”;

(6) DESC CONSIGNEE;

(7) DEGREE = 4 CARDINALITY = 4


Q5. Write SQL commands for the queries (i) to (iv) and output for (v) &
(viii) based on a table COMPANY and

CUSTOMER. COMPANY

CID NAME CITY PRODUCTNAME


111 SONY DELHI TV
222 NOKIA MUMBAI MOBILE
333 ONIDA DELHI TV
444 SONY MUMBAI MOBILE
555 BLACKBERRY MADRAS MOBILE
666 DELL DELHI LAPTOP

CUSTOMER
CUSTID NAME PRICE QTY CID
101 Rohan Sharma 70000 20 222
102 Deepak Kumar 50000 10 666
103 Mohan Kumar 30000 5 111
104 Sahil Bansal 35000 3 333
105 Neha Soni 25000 7 444
106 Sonal Aggarwal 20000 5 333
107 Arjun Singh 50000 15 666

(i) To display those company name which are having prize less than 30000.

(ii) To display the name of the companies in reverse alphabetical order.

(iii) To increase the prize by 1000 for those customer whose name starts with
„S‟

(iv) To add one more column totalprice with decimal(10,2) to the


table customer

(v) SELECT COUNT(*) ,CITY FROM COMPANY GROUP BY CITY;

(vi) SELECT MIN(PRICE), MAX(PRICE) FROM CUSTOMER


WHERE QTY>10 ;

(vii) SELECT AVG(QTY) FROM CUSTOMER WHERE NAME LIKE “%r%;

(viii) SELECT COMPANYNAME,CITY, PRICE FROM COMPANY,CUSTOMER


WHERE COMPANY.CID=CUSTOMER.CID AND
PRODUCTNAME=”MOBILE”;
Ans.
(i) SELECT C.NAME
FROM COMPANY C, CUSTOMER R WHERE
C.CID = R.CID AND PRICE < 30000;

(ii) SELECT NAME FROM COMPANY


ORDER BY NAME DESC;

(iii) UPDATE CUSTOMER


SET PRICE = PRICE + 1000
WHERE NAME LIKE “S%”

(iv) ALTER TABLE CUSTOMER


ADD TOTALPRICE DECIMAL(10,2);

(v)

COUNT(*) CITY
3 DELHI
2 MUMBAI
1 MADRAS

(vi)

MIN(PRICE) MAX(PRICE)
50000 70000

(vii)

AVG(QTY)
37500

(viii)
NAME CITY PRICE
NOKIA MUMBAI 70000
SONY MUMBAI 25000

You might also like