0 ratings0% found this document useful (0 votes) 51 views60 pagesComputer Science Practical File
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
d
LINGAYA’S
GROUP
choose to know
=
CENTRAL BOARD OF SECONDARY EDUCATION
Lingayas Public school
saket new delhi
APRACTICAL RECORD FILE 1S SUBMITTED TO DEPARTMENT OF COMPUTER SCIENCE FOR THE PARTIAL
FULLFILLMENT OF SSCE EXAMINATION FOR THE ACADEMIC SESSION: 2022-23
SUBMITTED BY: Ashish
HOD(COMPUTER):Mr. Roshan sir
CLASS: I2th Science
ROLLNG:
ACKNOWLEDGEMENTBt
| wish to express my deep sense of gratitude and |
indebtedness to our learnedteacher Mr Roshan sir .PGT COMPUTER
SCIENCE. Lingayas Public school for his invaluable help. advice and
guidance inthepreparationof this project.
lamalsogreatlyindebtedto our principal and
school authorities for providing me with the facilities and
requisitelaboratoryconditions formaking this practical file.
| also extend my thanks to a number of teachers my
classmates and friends who helped me to complete this practical
filesuccessfully.
fishish
CERTIFICATEThisistocertifythat Ashish .student of Class HIl.
Lingayas Public school has completed the PRACTICAL FILE during
the academic year 2022-23 towards partial fulfillment of credit
for the Computer Science practical evaluation of CBSE SSCE-2023
and submitted satisfactory report. as compiled in the following
pages,under my supervision.
Totalnumber of practical certifiedare:24
Internal Examiner External
Examiner
Date: School Seal Principal
BCONTENTSWorking with functions
Write a python program using a function to print
factorial number series fromn to mnumbers.
Write a python program to accept Lhe username Admin”
as the default argument and password 123 entered by
the user to allowlogin into the system.
Write a python program to demonstrate the concept of
variable length argument. to calculate the product and
power of the first 10 numbers.
Data File handling
Create a text file “intro.txt” in python and ask the user
towrite asingleline of text by user input.
Write a program to count a total number of lines and
count the total number of lines starting with f’. B’ and
T From the file dfh.txt.
Write a program to replace all spaces fromtext with ~
(dash) from the file intro.txt.
Write a program to know the cursor position and print
the text according to the below-given specif ications:
Print the initial position
Move the cursor to 4th position
Displaynext S characters
Move the cursor Lo thenext 10 characters
Print the current cursor position
Page 4Td
| Print next 10 characters from the current cursor
|
|
| 8 | Write a program to store customer data into a binary
| file cust.dat using a dictionary and print them on
i screen af Ler reading them. The customer data contains
1D as key. and name. city as values.
9 | Write a program to update a record from student.dat
| File by its rollno. Display the updated record on screen.
10 |Write a program to write data into binary file
| marks.dat. and display the records of students who
| scoredmore than 95 marks
\| Ty [Read o CSU File topS.ceu and print the contents in a
| proper format. The data for Ltop5S.csu file are as
following
| PTET Ly TE LT
HLRahul
SDhawan
' David Warner
Shreyas lyer
Ishan Kishan
2 |Read a CSU file topS.csy and print them with tab
delimiter. Ignore first row header to print in tabularForm.
Read a CSU file students.csu and print them with tab
delimiter. Ignore first. row header to print in tabular
Form,
Field?
DataType
StudentID Integer
Studentlame String
Score Integer
3 | Data Structure -Stack
WW | Write aprogramto implement astack for the employee
details (empno. name).
1S | Write a python program to check whether a string is a
palindrome or not using stack.
4 | Database management (MySQL Queries)
16 | Queries Set 1 (Fetchingrecords)
V1 | Queries Set 2 (Based on Aggregate Functions)
18 | Queries Set 3 (DDLCommands)
‘9 | Queries set 4 (Based on Two Tables)
20 | Queries Set 5 (Group by Order By)
5 | Python-MySQL Connectivity
21 | Write aMySOL connectivity program in Python Lo
Create adatabase school
Create atable students with the specifications —: charact.er(
performthe following operations:
© Insert tworecords init
o Display the contents of thetable
22 | Performall the operations withreference to table
~ students through MySQL—Python connectivity.
23 | Write amenu-driven program Lo store data intoa |
MySOL database named shop and table customer as |
Following:
1. Add customer details
2. Update customer details
3. Delete customer details
4. Display all customer details
24 | Modif y the above program and display the customer
details based on the following menu:
1 Display customer details by city
2. Display customer details by bill amount
3
4. Display customer details by category
Part. workingwithfunctions
1. Write apython program using a function to print factorial number
isplay customer details by name
jes fromn
tomnumbers.
def facto():
n=int(input.(Enterthenumber”))
f=1
foriinrange(Ln+l):
fri Enter the number:5
Factorial of 5 is: 120
»>
print.(Fact orial of “n.Facto()
2. Write apython program to accept username ‘Admin’ as default argument and
password 123 enteredby user to allowlogin into the system.
def user_pass(pass word.username= Admin’):
if password=="123:
print(YouhaveloggedinLosystem’)
else
print(Passwordisincorrectlll
password=input(“Enter thepassword:)
user_pass(password)
Enter the password: 123
You have logged into systen
== RESTART: C:
Enter the password:hello123
Password is incorrect!!!!!!
3. Write apython program to demonstrate the concept of variablelength
argument to calculate product and power of the first 10 numbers.
def suml0(“n):
total=0
foriinn:
total=total +i
print(Sumof first 10Numbers*.Lotal)
suml0(1.2.3.45.6.18.9.10)
picnic iii iin ini
caenenaarnnnnnanniannnnmrncnanenacnimensnnanssnmnanamenatnimmnamennnainmnnnamnnsnatniannn niesdef product 10(*n):
pr=l
foriinn:
pr=pr‘i
print(‘Product of first. 10 Numbers".pr)
product 10(12.3.4.5.6.18.9.10)
MDLAN, vs WORLD J
Sum of Finst 10 Numbers; 55
Product of fist 10 Nuabers: 3628800
Part 2Datafilehandling |
4. Create atext file “intro.tut” in python and ask the user to write a single line
text by user input.
def program)
_ . EstaR?: &:/Python 209
f=open(intro.txt”’w") 0 This is text file.
Lext=input(Enter the text”)
faurite(text)
F.close(
programi()
rote enrmmnnnnnnrnmnnenenne neieneaneie nen5. Writeaprogramtocount.atotal number of lines and count the total number of
lines starting with’. B.and'C’ fromthe file myfile.tut.
def program5()
withopen(“Myfile.txt’r’) asf
data=fl.readlines()
nes=0 File Contents:
Python is super and trending language
Allows to store the output in the files
A text file stores textual data
Binary files can handle binary data
ent_ Binary files use pickle module to store data
Fs SV files can handle tabular data
forlines in data: CSV files can be read easily using CSV reader object
ent_lines+= Total Number of lines are: 7
iflineslO} Total Number of lines strating with A are: 2
ent_At=l Total Number of lines strating with B are: 2
iflinesf0} Total Number of lines strating with C are: 2
cnt_B+=1
iflines{O}
ont_Ct=1
print(TotalNumber of linesare:.cnt_lines)
prin(TotalNumber of linesstratingwithfare”.cnt_A)
print(TotalNumber of linesstratingwithBare”.cnt_B)
print(TotalNumber of linesstratingwithCare”.cnt_C)
programS()
6. Write aprogramtoreplace all spaces from text with - (dash) fromthe file
intro.txt.
def program6():
ent =0
withopen(intro.txt’ rash:
data=fl.read()
data=datareplace(™
)
withopen(intro.tnt’’w')osft Pecan
Ahmedabad, Gujarat
Mumbai ,Maharashtra
Indore ,Madhya-Pradeshgn ini i etic i ing
seecnsanenainc nett NnCLttnANAs RE IANERNACEENASCNEARATAANANeCNCtnMnntatttnieaiteaiatnsitet
Flwrite(data)
withopen(intro.txtr’) as fl:
print(fl.read())
program6()
‘| Write aprogram to know the cursor position and print the text according to the
below-given specifications:
a. Print the initial position e. Print the current cursor position
b. Move the cursor to 4th position f. Print next 10 characters from
c. Display next § characters current position
d, Movecursor tonext 0 characters
def progr am IC)
f=open(“intro.tut’r”) area an
print(‘Cusror initial position.”) Dispakg ves ta i ei,
print(F.tell()) ne
F.seek(4.0) int cans curseat postion
print(Displayingualues fromSth position) | (ss. gu 1 auc fen c's ens pn,
print (F.read(5)) he
F.seeh(10.0) =
print(F.tell())
print("Print.cursor scurrentpostion’)
print(f.seak(.0))
print (Displayingnext 10 charactersfromcursor'scurrent postion. )
print.(f.read(10))
program \()
8. Create a binary file client.dat to hold records like ClientID. Client. name. and
Address using the dictionary. Write functions to write data, read them, and print.
onthe screen.
import pickledef File_create():
f=open(“client.dat™" wb")
cno=int(input(EnterClientID" ))
cname=input(Enter Client Name'”)
address =input (Enter Address’)
ree={enolename.address]}
pickle.dump(rec.f)
defread_data():
f =open(“client.dat"”rb”)
print(Datastoredinfile...”)
rec=pickleload()
foriinrec:
lenter ciient 1D:101
print(reclil) Enter Client Name:Shailesh
Enter Address :Ahmedabad
fil tel) See An AMAR RA EA ERR RRER AR EE AES
Ne_create Data stored in File...
({'Shailesh', 'Ahmedabad']
read_data()
9. Urite a program to update arecordfrom student. dat file by its rolino, Display
the updatedrecordon screen.
import pickleas p
;
t t
| |
i i
i i
i i
t t
t t
| |
t t
t t
i i
1 i
i t
| |
{ !
t i
i i
t t
t t
t t
| |
t t
t t
i t
| i
| |
i i
t i
t t
i i
1] prine""18)
| prin t
t t
t i
1 i
| {
t t
i i
t t
t t
i i
| |
t !
t i
i i
t i
1 i
i i
t t
i t
t t
i i
t t
| |
i i
t t
i i
t t
t t
| |rec=[]
Found=0
f=open(“student.dat’rb+")
r=p.load(f)
print(ExistingRecord:.r)
ro=int(input(“Enterroll notoupdate’))
Foriinr’
ifro==il0k
if ]=input(Enternewname”)
found=1
break
if found=
print (recordnot found..”)
alse:
F.seeh(0)
p.dump(r.f)
print(RecordUpdated..”)
F.close()
fl=open(’student.datrb¥) sisting naswedeflanle a
“| Enter roll no to update:101
r=pload(fl) Enter new nane:Vikas
Z a Record Updated...
print(UpdatedRecord:r) Be EE ital
Flelose()10. Write a program to write data into binary file marks.dat and display the
records of students who scored more than 95 marks.
impor tpickle
def search_95plus():
f= open("marks.dat”ab”)
while True:
rn=int(input(“Entertherollno:))
sname=input(“Enter thename™)
morks=int(input (“Enterthemarks: ))
rec=[]
data=[rn.sname.marks]
rec.append(data) Enter the rollno:1
pickledump(rsct Enter the name:Aryan
: . ., | Enter the marks:85
ch=input{"Wnatmorerecords?¥es") Wnat more records?Yes:y
if ch lower()not in yes: Enter the rollno:2
Enter the marks: 96
F.close() Wnat more records?Yes:y
f= open(“marks.dat’rb”) Enter the rollno:3
Enter the name:Prakash
Enter the marks:98
try Wnat more records?Yes:y
ent=0
whileTrue: Enter the rollno:4
_ Enter the name:Priya
data=pickleload(f) Edkas che markes92
forsindata Wnat more records?Yes:n
7 Record: 1
> 95°
if s[2]>95: ie
ent t=] Name: Debanjan
print("Record: cnt) Marks: 96
o ' Record: 2
print("RollMO".s101) RollNO: 3
print(“Hame’s[1]) Name: Prakash
print("Marks"s[21) Bae as 22
1
|
i
|
|
|
|
|
|
i
i
|
|
i
\
i
|
i
i
i
|
i
i
i
i
= |
break Enter the name:Debanjan
i
i
|
|
\
i
i
i
|
\
\
i
|
|
|
i
i
|
|
i
|
i
i
|
|
nndexcept Exceptio:
F.close()
search_95plus()
ze
Tl. Read a CSU File top5.csv and print the contents in a proper format. The data for
topS.cev file are as following:
def prol():
withopen(top5.
d=reader(F)
data=list(d)
prol()
ern
HL Rahul
SDhawan
David Warner
Shreyas lyer
Ishan Kishan
fromesvimportreader
csv asf
Ur
['SWo', 'Batsman', 'Tean', 'Runs', 'Highest!]
U1", (RL Rabul', "HHI", "670', 1324")
['2', 'S Dhawan', 'DC', '618', '106#")
['3', "David Warner’, 'SRH', '548', '85*')
['4", "Shreyas Tyer', ‘Dc’, '519', '88+"]
('5', "shan Kishan', 'MI', '516", 199")
header to print in tabular form.
T2. Read a CSU File top5.csu and print them with tab delimiter. Ignore first row
fromesvimportreader
def prol2():
f= open("e\\top5.csu"'r’)
dt=reader(f.delimiter=") ca
$ Dhawan
headr_row=next(dt)
“ii David Varner
data=list(dt) § 1
f closet) bene
. Tshan Kishan
Foriindata:
leinratcnsnmitanitmanmintnnanertnminmcrmatiintnianritainaitatitiniinntieinm item aniiittiineitminitaiiininiiteaai eit ianite tinea mitt te sed{TR RRR RRR IRR IE TIENT RN NA NN AEN
for jini’
print(j”\tend="")
print()
prol2()
rowheader to print in tabular Form.
13. Read a CSU file students.csu and print them with tab delimiter. Ignore first
Data Type
StudentD Integer
Studentlame String
Score Integer
fromesvimport writer
def prol3():
WCreateHeaderFirst
f= open(‘result.csu™'w".newline=\n)
dt=writer(f)
F.close()
Uinsert Data
f= open(‘result.csu’"a’newline=\n)
while True’
st_id= int (input (Enter Student ID"))
st_name =input(“Enter Student name:)
st_score =input.(‘Enter score”)
dt=writer(f)
dtwrit er ow(('Student_ID’Studentllame Score l)
dt.writerow([st_idst_name.st_score])
[inter student 1D:1
Jinter Student nane: Shekhar
finer seore:52
Jiant to insert More records?(y ot 1):y
|Bnter student 1D:2
Jinter Student nane:Manoj
Jinter score:65
Joant to insert More records?(y or ¥):y
Janter student 10:2
lnter ‘Student name: Swadesh
[Enter score:58
Jiant to insert More reootds?(y or ¥):0
pe has been added
>»
i.put (Want toinsert Morerecords?(yor¥)")
ch=ch.lower()
if chh
break
print Recordhasbeenadded.”)
f.close()
prol3()
Part. 3DataStructure
lriven python program to implement stack operation.
14. Write amenu:
| def check_stack_is€mpty(stk):
if stk==I1
return True
else:
returnFalse
HAnemptylisttostorestackelements. initiallyempty
sl]
top=NonefThisistop pointer for pushandpop
def main_menu():
while True:
print(Stacklmplementation’)
print(1-Push”)
print(2—Pop")
print(“3—Peek”)
print(4—Display”)
|
|
i
'
\
'
\
|
|
|
'
i
|
i
i
\
|
|
|
i
|
\
\
|
|
i
i
i
|
i
\
i
i
|
|
i
\
\
i
|
|
|
'
i
|
\
\
i
|
|
\
|
i
\
|print (S-Exit”)
ch=int(input(“Enter theyour choice”)
if ch==1
el =int(input( Enter the value to pushanelement”))
push(s.el)
elif ch==2;
e=pop_stack(s)
if e=="UnderFlow™
print(Stackisunderflow!”)
else
Stack Implementation
print(Element popped: .e)
e=pop_stack(s)
if e=="UnderFlow™
print(Stackisunderflow!”)
else
print(Theelement ontop is”.e)
elif ch==4 cree
display(s) See
elif ch==!
break
else:
print(“Sorry,invalidoption”)
def push(stk.e):
stk.append(e)Lop=len{stk)-1
def disploy(sth)
if check_stack_isEmpty(stk):
print(StackisEmp ty’)
else!
top=len(stk)-1
print(stk[t op]”-Top”)
Foriinrange(top-l.-1-1):
print(sthlil)
def pop_stack(stk):
if check_stack_isEmpty(stk):
return UnderFlow”
else:
e=stkpop()
iflen(stk)==0
Lop =None
else:
top=len(stk)-1
returne
def peek(stk):
if check_stack_isEmpty(sth):
return UnderFlow™
else:
top=len(stk)-1
returnstk[top]ARR RRR RRR ENN ENN
15. Write aprogramtoimplement.a stack for the employee details (empno,name).
stk=[]
top=-]
def line():
print(~"100)
defis€mpty():
global stk
if stk==[
print(“Stackis empty!l!’)
else:
None
def push():
global stk
global top
empno=int (input( Enter the employeenumber topush"))
ename=input (Enter theemployeenametopush")
stk.append([empno.enamel)
top=len(stk)-1
def display():
global stk
global top
if Lop’
isEmpty()
alse:
top=len(stk)-1
|
i
i
i
|
|
|
|
i
|
'
|
|
|
i
i
i
i
i
i
\
|
i
|
|
i
i
|
i
i
i
i
|
'
i
i
'
|
|
i
|
'
i
|
|
i
i
i
|
i
\
i
i
|
L
es dein
‘er neg te ts uh. 23
‘eae Seep ae ts pbaprint (stk[top].”<—top")
foriinrange(top- 1-1-1):
print(sthlil)
def pop_ele():
global stk
global top
if Lop==-1:
isEmpty()
else:
stk.pop()
Lop=top-l
def main():
while True!
line()
print (LPush")
print 2.Pop")
print (‘3.Display”)
print (4.Exit”)
ch=int(input("Enter your choice’ ))
if ch==Fnm
push()
print(ElementPushed")
elif ch==2:
pop_ele()
elif ch==3:display)
elif ch==4
break
else:
print("InvalidChoice’)
stack.
16. Write apython program to check whether astring is apalindrome or not. using
stack=[]
top=-]
Hpush function
def push(ele)
globaltop
Lop #=1
Hpopfunction
def pop():
globaltop
ele=stackLtop]
top-=1
returnele
#Functionthat returns lif stringisapalindrome
defisPalindrome(string):
globalstack
length=Llen(string)
HAllocatingthememory for thes tack
stack=[0]*(length+1)
r
t
t
'
i
t
'
'
t
t
I
i
i
i
i
i
'
t
t
'
i
‘
i
t
t
'
|
t
I stackltop]=ele
t
t
i
i
t
t
'
i
‘
'
t
t
‘
i
i
1
t
i
i
i
t
t
‘
i
i
i
t
'
Leanne tnnannnnannnnnnnnnnnnnnnannnnnnsnannemnnntnnnEnetnnnnnaenennnnnnnteteinnttielelse’
returnfalse
b»
it=1 seems ESIC thn Peat pf ees
ter iy hin
return True Mee, the sting i a pulidrne
b»
string=inpul(EnterstringLo check”) [ses HSH: thn Porat py
iter tig to ey
ifisPalindrome(string): I the srg ist a piinene
print(‘Yes.thestringis apalindr ome”)
print( No, thestringisnota palindrome’)
Part Ysql queries
1. Consider the following MOVIE table and write the SQL queries based on it.
iiFindingthe mid
mid=length//2
i=0
while i150000 and <1000000;
e)select moviename from movie where type ='action' or
type='romance' ;
NE EES Cae eC cee CRs] eet as CUMS] eee aoe
eee Sete
roe
Cate
3 rows in set (8.08 sec)iysql> select moviename from movi es
ec
ey yoo)
aT
Sac
|
|
ee
|
z
|
|
|
|
gs
t
ne
Harshil
roy Pe
Une: eet
fey
Manish
Pes
emer
a) Display the total charges of patient. admit.tedin the month of November.
b) Display the eldest patient withname and age.
c) Count. the unique departments.
4) Display an average charges
Answers:
a)select sum(charges) from patient
where dateofadm like '%-11-%';
i
:
;
i
i
:
i
i
t
:
i
i
i
'
|
i
i
i
t
i
:
i
|
i
5
t
i
a
i
i
i
'
:
I
i
i
t
t
t
i
'
i
I
i
i
t
i
i
i
:
i
i
i
H
| Co3. Suppose your school management has decided to conduct. cricket matches
between students of Class Hl and Class Hl. Students of each class are asked to
join any one of the four teams — Team Titan, Team Rockers, Team Magnet and
Team Hurricane. During summer vacations, various matches will be conducted
between these teams. Help your sports teacher to do the following:
a) Createadatabase” Sports
b) Createatable” TEAM with following considerations:
a. It shouldhave a column TeamlD f or storing an integer value between | to
9. which refers to unique identification of ateam:
b. Each TeamlD should have its associated name (TeamName), which should
be astring of length not less than 10 charactersc. Usingtable level constraint, make TeamlD as the primary key.
c) Show the structure of the table TEAM using a SQL statement.
d) fis per the preferences of the students four teams were formed as given
below. Insert. these four rows in TEAM table:
a. Row ¥ (1. Tehtka)
b. Row 2(2.Toofan)
c. Row 3:(3.Aandhi)
d. Row 3:(4.Shailab)
e) Show the contents of the table TEAM using a DML statement.
f) Now create another table MATCH_DETAILS andinsert. dat.aas shown below.
Choose appropriate datatypes and constraints for eachattribute
Match | MavchDat | FiretTeaml] SecondTeaml |FireUTeamSeor | SecondleamScor
D e D D e e
20aviele
0 4
me |eoevee| 3 4 156 158
mg | URE) 3 86 81
m4 mone 2 4 65 61
ins spay 1 4 Se 88
me | MANET 3 31 68
Answers:
a) create database sports;
|
i
i
t
|
'
i
i
i
{
|
'
'
i
i
i
i
i
i
{
|
t
i
i
i
{
|
'
i
mi 1 2 107 93 |
{
i
i
i
i
{
|
'
i
i
i
{
|
'
i
i
|
i
i
i
i
{
|
t
i
i
i
i
i
i
|
|
i
i
‘
i
|
|
|
i
i
|
i
i
i
i
|
|
i
i
'
|
|
|
|
i
i
|
i
i
i
i
|
|
i
i
'
i
|
|
|
i
i
|
i
i
'
i
|
|
i
i
Lcreate database sports
Pa ee oe tt ae re
ports;
Bale)
b) Creating table with the given specification
create table team
(teamid int(1),
teamname varchar(10), primary key(teamid));
c) desc team;
Inserting data:
mgsql> insert into team values(1, 'Tehlka');
into team
Pa
eee Cr
Coe a
een
oo
nai lab’)Show the content of table - team:
select * from team;
Creating another table:
create table match_details
-> (matchid varchar(2) primary key,
-> matchdate date,
-> firstteamid int(1) references team(teamid),
-> secondteamid int(1) references team(teamid),
-> firstteamscore int(3),
-> secondteamscore int(3));
create table match_detail
riser Metall SI testes a
eee Re OMe rea eG CD
ondteamid int(1) m(teamid),
i liteelar
Etec tren tees
Query OK, @ rows affected, 4 warning
a pennant nanan nt et tennennnnnnnennanennne en enennininninnnenneanennnnnnnnnnrennnnie nnieininelel
renennenmnnrnninenintennnnnennnintntntnnnnnnenernrnnntmnnnninnnntnTrtnetesntttithrocrieeeernnenannnntnnnnniinetnnnnaientaanten atin, etnnNsniiaiant eA erat,
sql> select * From
Pot eeraed
Pooteeeaer’
Porteetae!
4 Write following queries:
a) Display the mat.chid, teamid, tears core whoscored more than 10 in first.
ining along with team name.
b) Display mat.chid, teamname and secondteamscore between 100 to 160.
c) Display matchid. Leamnames along with matchdates
d) Display unique Leam names
e) Display matchid and matchdate played by finadhi and Shailab.
Answers:
a)select match_details.matchid, match_details.firstteamid,
team. teamname ,match_details.firstteamscore from
match_details, team where match_details.firstteamid = team.
teamid and match_details.first
area
matchdate | firstteami
it
1
1
r
r
r,
}
i
Lb)select match_details.matchid, match_details.firstteamid,
team. teamname,match_details.firstteamscore from
match_details, team where match_details.firstteamid =
team.teamid and match_details. firstteamscore>70;
aR)
c)select matchid, teamame, firstteamid, secondteamid,
matchdate from match_details, team where
match_details. firstteamid = team.teamid;
d)select distinct(teamname) from match_details, team where
match_details.firstteamid = team.teamid;
ee ttlcnncenaieinnrmeaeintesnntiiit
re) from natch details, tea
e)select matchid,matchdate from match_details, team where
match_details.firstteamid = team.teamid and
team. teamname in ('Aandhi', 'Shailab');
5. Consider the following table and write the queries
itemno | Item dcode qty unitprice stockdate
S005 Ballpen 102 100 10 2018/04/22
$003 Gel Pen 101 150 6 2018/03/18
$002 Pencil 102 25 5 2018/02/25
$006 | Eraser 101 200 3 2018/01/12
$001 | Sharpner 103 210 5 2018/06/11
S004 Compass 102 60 35 2018/05/10
r
i
I
t
i
i
|
i
i
i
i
}
i
i
i
|
i
i
i
t
:
i
i
i
i
|
|
i
i
i
|
|
t
I
t
i
i
|
i
i
i
i
i
|
|
t
i
i
|
|
t
i
i
i
|
|
i
i
|
|
|
\
|
|
i
i
|
i
i
|
i
i
i
|
|
|
i
|
|
i
|
|
i
t
i
i
|
|
i
|
i
i
|
|
\
|
|
i
i
t
i
|
|
|
i
'
|
|
|
i
|
i
i
|
|
i
i
Donnan ean aPP RCI ONE E EE TERE ELEC CE OEE EEE ECLECTIC
soog
Ad Papers 102 160 5 2018/01/11
a) Display all the items inthe ascending order of stockdate.
b) Display maximum price of items for each dealer individually as per dcode from
stock.
c) Disployall the items in descending orders of itemnames
d) Display average price of items for each dealer individually as per doce from
stock which avergae price is more than5.
e) Diisplay the sum of quantity for each deode.
| Answers:
a) select * from stock order by stockdate;
(Easier
SEY
ear eee ae
c) select
from stock order by item desc;
I
1
|
i
i
t
1
|
i
i
|
t
i
i
\
|
I
1}
|
i
t
t
}
|
i
1
i
1
}
|
i
t
i
i
1
|
i
t
1
1
|
i
{
|
i
|
|
|
I
1!
}
i
{eee
Log
d)select deode,avg(unitprice) from stock group by dcode
having avg(unitprice)>5;
t
I
i
t
:
i
t
t
t
I
I
t
i
t
i
I
t
t
t
t
I
I
i
i
t
i
i
'
i
I
t
i
i
t
t
| Write aMyS0L connectivity programin Python to
Create a database school
Createa table students with the specifications — ROLLNO integer. STNAME
character(10) in MySQL and perform the following operations:
o Insert two records init
pio Displaythe contents of the table
2. Performallthe operations with reference totable’ students’ through
MySQL—Python connectivity.
Answers:
1. Using pymysql - Code:
import pymysql asms
HunctiontocreateDatabaseasperuserschoice
def c_database():
try
dn=input.(EnterDatabaseName=")
c.enecute("create database{}’.format(dn))
c.execute("use{}".format(dn))
print( Database created successfully’)
exceptExceptionasa:
print(Database€rror’.a)
HfunctionLoDropDatabaseasperusers choice
def d_database():
try:
dn=input (“Enter Databaselametobedropped=")
c.execute (“drop database{}" format(dn))print.(Dat.obasedeletedsucessfully’)
except Exceptionasa:
print (DatabaseDropError’.a)
fiFunctiontocreateTable
def c_table():
try
cexecute(“createtablestudents
(
rollnoint.(3)
stnamevarchar(20)
y
=)
print. Table created successfully’)
exceptExceptionasa:
print. (Create Table Error’)
fPunctiontolnsert. Data
def e_data():
try:
while True:
rno=int(input.(Enterstudentrollno="))
name=input. (‘Enter student name=")
cexecute(use{} format('school’))
cexecute(insertintostudentsvalues({}.{}): format(rnoname))
db.commit()choice=input(Doyou want. to addmorerecord=")
if choice in"Wn™
break
except Exceptionasa!
print(InsertRecordError’.a)
HFunctionLoDisplayData
def d_data():
try:
cexecute("select”fromstudents’)
data=c.fetchall()
foriindata:
print(i)
except Exceptionas a
print. (Display Record€rror’.a)
db=ms.connect(hast="localhost user=root password="root”)
c=db.cursor()
while True:
print(MENU\nI.CreateDatabase\n2.DropDatabase\n3.Create Table\n4.Insert
Record \n5. Display €ntireData\n6.Exit”)
choice=int(input (Enter your choice="))
¢_database()
elif choice==2:
d_database()
elif choice==3:i] c-toble()
==4f
elif choice
elif choice
==6
alif choice
print(‘Wrongoptionselected’)seu
1, Create Database
2, Drop Database
3. Create Table
4, Insert Record
5. Display Entire Data
6, Exit
Enter your choice=1
Enter Database Nane=school
Database created successfully
ve
1, Create Database
2. Drop Database
3, Create Table
4, Insert Record
5. Display Entire Data
6. Bxit
Enter your choice=3
Table created successfully
MENU
1. Create Database
2. Drop Databas
3. Create Table
4. Insert Record
5. Display Entire Data
6, Exit
Enter your choicecl-6>=4
Enter student rollno=11
Enter student nane=Raj
Do you want to add more record=n
MENU
1. Create Database
2. Drop Databas
3. Create Table
4. Insert Record
5, Display Entire Data
6. Exit
Enter your choicecl-6>=5
(11, 'Raj')
MENU
1. Create Database
2. Drop Database
3. Create Table
4, Insert Record
5. Display Entize Data
6. Exit
Enter your choice=62. using mysqlconnector
import mysql.connectorasms
db=ms.connect.(host= localhost user="root” passwd= "root. dat.abase='school’)
en=db.cursor()
def insert_rec():
try
while True:
rn=int(input Enterrollnumber:))
sname=input("Entername: )
marks=float(input( Enter marks: ))
gr=inpuL( Enter grade*)
cn.execube( “insert into students
values({}. {}.(}. {7 format(rn.sname.marks.gr))
db.commit()
ch=input(‘Wantmorerecords?Press(N/n)tostop entry”)
if chin Wn
break
except Exceptionase:
print(Error’.e)
def update_rec()
try:
rn=int(input (‘Enterrollnoto update: ))marks=float (input(Enternewmarks* ))
gr=input (Enter Grade’)
cn.execute( update students set marks={}.grade={} where
rno={}"format(markegr.rn))
db.commit()
except Exceptionase:
print(Error’e)
def delete_rec():
try
rn=int(input(Enterrollnotodelete™))
cn.execute(deletefromstudents where rno={}format(rn))
db.commit()
except Exceptionase:
print(Error’e)
def view_rec():
try
cn.execute(“select“fromstudents )
import mysql.connect orasms
db=ms.connect(host= localhost user="root” passwd="root database='school’)
en=db.cursor()
definsert_rec():
try:
while True:
Dc ca cecalen=int(input(“Enter rollnumber”))
sname=input(“Enter name: )
marks=float(input(“Enter marks”))
gr=input (Enter grade.)
cn.execute(insertinto students
values({}.{}.{}.{})" format (rn.snamemarks.gr))
db.commit.()
ch=input (Wan tmorerecords?Press(N/n)tostop entry”)
if chin Nn
break
except Exceptionase:
print(Error’.e)
def update_rec(?:
try:
rn=int(input (“Enter rollnotoupdate™))
marks=float(input(‘Enter newmarks® ))
gr=input (Enter Grade”)
cn.execute(‘updatestudents set marks={}.grade="{} where
rno=€}"format(marks.gr.rn))db.commit()
except Exceptionase:
print(Error’e)
def delete_rec():
try:
rn=int(input (‘Enterrollnoto delete’”))
cn.execute(delatefromstudent.swhererno={}"format(rn))
db.commit()
exceptExceptionase:
print(“Error’e)
def view_rec():
try
cn.execute(select."fromstudents’)
data=c.fetchall()
foriindata
print(i)
except Exceptionase:
print(Error’e)
while True:
Tr
i
i
i
|
|
|
\
i
|
|
|
\
i
i
|
|
i
\
i
|
|
i
|
i
i
|
|
|
i
i
|
i
i
|
|
|
i
|
|
\
i
|
|
i
i
|
|
i
i
\
'
|
|
|
i
|f print (MENU\nL. Insert Record\n2. Update Record \n3.Delete Record \n4.DisplayRecord
\n5.Enit")
ch=int(input (Enter your choice="))
if ch==1:
insert_rec()
elif ch==2:
update_rec()
elif ch==3:
delete_rec()
elif ch==4
view_rec()
elif ch==5
break
alse:
print(‘Wrongoptionselected’)
except Exceptionase:
print(Error’.e)
while True:print (MENU\nL Insert Record\n2.UpdateRecord\n3.DeleteRecord\n4.DisplayRecord
\n5.Enit”)
ch=intCinput(Enteryour choice="))
if ch==1:
insert_rec()
elif ch==2:
update_rec()
elif ch==3:
delete_rec()
elif ch==4:
view_rec()
elif ch==5:
break
else:
print(“Wrong option selected”)
Output :2, Insert Record
2. Update Record
3. Delete Record
4, Display Record
5. Exit
Enter your choiceci-4>=1
Enter roll nunber:11
Enter
Enter
Enter :
Want more records? Press (N/n) to stop entry:y
Enter roll nunber:114
Enter nane:Vipul
‘Enter grade:A2
Want more records? Press (N/n) to step entry:n
sexu
inert Record
Update Record
Dele!
Display Record
Exit,
Enter your choicecl-s>=4
(1, ‘Aneita’, Decimal ('@8.00"), "A2")
(102, ‘Jay*, Decimal('98.00'), 'AL')
(111, ‘Sagar’, Decimal ("96.00'), 'A1")
(114, ‘Vipul’, Decdnal ("63.00"), 'A2")
ven
1. Insert Record
i
'
i
1
t
i
1
1
i
t
1
i
t
'
i
| 2. Update Record
1
1
i
t
i
t
t
i
1
'
i
1
1
1
‘
Record
3, Delete Record
4. Display Record
5. Exit
Enter your choiceci-4>=2
Enter rolino to update:1
gnter new marks: 98
Enter Grade:A1
ven
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5, Exit
Enter your cheicecl-t>=4
(1, ‘Aneita’, Decimal('98.00"), 'A1")
(102, 'Jay", Decinal('98.00"), 'AL')
(211, ‘Sagar’, Decimal ("98.00"), 'A1")
(114, ‘Vipul’, Decimal ("83.00"), 'a2")
3. Write amanu-driven program to store data into a MySQL database named shop
and table customer as following:
eee renee eee neces eee
Pou 2
L1. Add customer details
2. Update customer details
3. Delete customer details
4. Display all customer details
import mysql.connectorasms
db=me.connect(host="localhost user=root.” pasawd="root” daLabase="mydb’)
en=db.cursor()
definsert_rec():
try
while True:
cid=int(input(“Enter customer id”)
cname=input(“Entername:)
city=input(“Entercity”)
bill_amt=float(input(“Enter bill amount"))
cat=input(Enter category”)
cn.execut e(“insert.into customer
values({}{}.€¥.{}. (4) f ormat(cidcname.cit ybill_amt.cat))
db.commit()
ch=input(‘Wantmorerecords?Press(N/n)tostop entry’)
if chin Un:
break
except Exceptionase:
print(“Error’.e)
def update_rec():try
cn.execute(‘select “fromcustomer’)
data=enfetchall()
foriindata:
ci=il0]
ena=il]]
ct =il2]
b=i[3]
c=i{]
cid=int (input Enter customeridt oupdate: ))
if cid==ci:
ch_cname=input("Want toupdatellame.Press'¥)
if ch_cname.lower()=
else’
ename=cna
ch_city=input ("Want toupdatecity.Press'¥")
if ch_city.lower()=='y:
city=input(“Enter new city”)
else
city=ct
ch=input.(Wanttoupdatebillamount.Press'¥:")
if ch.lower()=
bill_amt=float(input(Ent er newbill amount)
else
I |
: '
t '
: '
t i
: i
i i
i i
i i
i t
1 i
4 '
} i
I I
t '
' '
' '
: i
4 '
I I
i i
t '
1 '
4 i
|
t t
' !
t i
4 t
i cname=input(Enternewname™) i
t '
t i
t t
; i
I I
t '
' '
i i
: i
|
t t
t i
t '
' i
; i
i I
' !
' '
: i
4 '
4 t
I I
t '
t '
t '
t tch_cat=input (‘Want LoupdateCategoryPress ¥:")
if ch_cat.lower()=
cat=input(Enternewcategory:)
else:
cat=c
where cust_id={}". format (cname.city.bill_amt.cat.cid))
db.commit()
alse:
print (“Record Not Found...)
exceptExceptionase:
print(Error’e)
def deleLe_rec():
try
cid=int(input(“Enterrollnotodelete™))
cn.execuLe( “delete fromcustomer where cust_id={}".format(cid))
db.commit()
exceptExceptionase:
print(Error’e)
def view_rec():
try
cn.execut e(select *fromcustomer’)
data=cnfetchall()
ent=0
cn.execute("update customer set cname={}\city={}.bill_amt={}.category={}°a a 4
foriin data: i
cnt=cnt+] |
print (Record”.cnt) i
print (~"50)
print (‘Customer if0]) i
print (Customer Name’ ill])
print (‘City il2])
print (Bill Amount” i[3]) i
print (Category iL4]) |
print.(~"S0)
except Exceptionase: i
print(Error’e) |
while True’ i
print (“MENU\nL Insert Record\n2. Update Record \n3.DeleteRecord \n4.DisplayRecord
\nS.€xit") i
ch=int{input (Enter your choice=")) |
if ch==1: |
insert_rec() |
elif ch==2 i
update rec() |
elif ch==3; :
delete_rec() |
calif ch==4 |
view_ree() i
|
i
elif ch==5:break
else:
print(Urong option selected")
Output:
menu
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5. Exit
Enter your choiceci-4>=1
Enter custoner id:
Enter nane:Shashank
Enter city:Bhuj
Enter bill anount:2500
Enter category:Silver
Want more records? Fress (N/n) to stop entry:n
Menu
4. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5. Beit
Enter your choiceci-4>=4
Record: 1
customer xD: 102
Customer Wane: Vishruti
City: Ahmedabad
Bill Anount: 1500.00
Category: Silver
Record: 2
customer xD: 104
Customer Wane: Ankit
City: Ahmedabad
Bill Anount: 3200.00
category: Platinun
Record: 3
Customer ID: 108
Customer Nane: Shashank
city: Bhuj
Bill Anount: 2500.00
category: Silver
Ln
LnDO rest neva metal lan srs Oud eee teen ave beh Leeann elias CD
Record: 4
Custoner 7D: 110
Custoner Nane: Heena
city: Baroda
BALL Amount: 1500.00
Category: Colden
saw
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5. Exit
Enter your choiceci-#>=2
Enter custoner id to update:102
Want to update Wane, Press 'Y':y
Enter new nane: Sujata
Want to update city, Press '¥!:n
Want to update bill anount, Press 'Y':y
Enter new bill anount:3000
Want to update category, Press 'Y':y
Enter new category:Golden
Data Updated successfully.
sew
1. Insert Record
2. Update Record
3. Delete Record
4, Display Record
5. Bxit
Enter your choicecl->=3
Enter custoner id to delete:110
Record Deleted
og
1. Insert Record
2. Update Record
4. Display Record
5. exit
Enter your choicect-d>=5
following manu:
4, Modify the above program and display the customer details based on the
1. Display customer details by city
2. Display customer details by bill amount
3. Display customer details byname
4. Display customer details by categoryimport mysql.connect. orasms
db=ms.connect(host= localhost ”.user= "root passwd="root dat abase=mydb)
en=db.cursor()
def byCity():
try
cit y=input (Enter citytosearch:)
cn.execut.e(“select*fromcustomer where city={}".format(city))
dat.a=cn.fet.chall()
ifdata!=[k
ent=0
Foriindata:
ent=cnt+]
print(~"100)
print(Record’.cnt)
print(‘~"100)
print(“Customer ID:"il0])
print(CustomerName™ ill)
print (City il2])
print (Bill Amounti[3])
print(‘Category™i[ 4)
else’
print (Norecordsfoundfor city “city)
except Exceptionase:print (‘Error“e)
def byBill Amt():
try:
ba=input (“Enter the bill amount”)
cn.execute("select* from customer wherebill_amt={}"format(ba))
data=cn.fetchall()
ifdatol=[F
cnt=0
foriindata:
ent=cnt+]
print(‘~"100)
print(Record™.cnt)
print(‘~"100)
print(Customer ID"iL0])
print(“CustomerName-illl)
print (City il2])
print (“Bill Amount”i[3])
print(Category:iL4])
else:
print. Norecordsfoundforbillamount. ba)
except Exceptionase:
print (‘Error’e)
def byHlame():name=input(Enterthename: )
cn.execut.e("select.“fromcustomer where cname= {}”.format(name))
data=cnfetchall()
if datal=[}
cnt=0
foriindata
cnt=cnt+]
print(‘~"100)
print(‘Record:.cnt)
print(~"100)
print(Customer ID" il0])
print(‘CustomerName* ill)
print (‘City il2])
print (“Bill Amount" il3])
print(Category: il 4])
else:
print(Horecordsfoundfor”.name)
except Exceptionase:
print(Error.e)
def byCat():
try
cat=input(“Enterthecat.”)
cn.execut e("select"Fromcustorner wherecategory={}"format(cat))data=cn.fetchall()
if datal=[}
ent=0
foriindata
ent=cntt]
print(~"100)
print(‘Record:cnt)
print(~"100)
print(CustomerID:.i[0))
print(CustomerName™ill])
print( City" il2])
print(BillAmount“i[3])
print(Category- ill)
alse
print(Norecordsfoundf orcategory”.cat)
except Exceplionase:
print(Error’e)
while True:
print”
MENU
Wisplay customer detail sby city
2.Displaycustomer detailsbybillamount
3.Displaycustomer detailsbynamea
4Displaycustomerdetailsbycategory
S.Enit.
*)
ch=int(input(“Enteryour choice="))
if ch==
byCity()
elif ch==2:
byBillAmt()
elif ch==3:
byllame()
elif ch==4
byCat()
alse:
print(Wrongoptionselected’)
Output:[ORR RARER TRENT NIA
END
1.Display custoner details by city
2.Display customer details by bill asount
3.isplay custonar details by name
4,isplay custoner details by category
S Exit
Enter your cheioe=2
Enter the bill amount:3000
Record: 1
Customer 1D: 102
Customer Nae: Sujata
City: Ahmedabad
BA11 Amount: 3000.00
Category: Golden
venus
L.Display customer details by city
2 display customer details by bill amount
3.Display customer datails by nane
4.Display customer details by category
Slexit
Enter your choice=3
Enter the nane:Ankit
Record: 1
[customer 1p: 104
| Customer Name: Ankit
City: Ahmedabad
Bill Amount: 3200.00
Category: Platinum
venus
L.Display customer details by city
2.bisplay customer details by bill amount
3.Display custoner details by nane
‘Display customer details by category
SlBxkt
Enter your choice<1-4>=4
Enter the cat :Golden
Reoord: 1
{Customer 1D: 102
Customer Name: Sujata
City: Ahmedabad
Bill Anount: 3000.00
Category: Golden
ENN
L.Display customer details by city
2.Display customer details by bill anount
3.Display customer details by nane
4.Display custoner details by category
S.Bxit
Enter your choice=5
ge 3.
Teleenciensiniansnsaneie hinnesmnecnaunnininnienceeantiein-anrtjnmtinentiainnmemninneninnnanminennesn inineninlind