Shreyash - Tiwari 2022-23 Report - File

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 86

COMPUTER SCIENCE(083)

COMPUTER SCIENCE
REPORT FILE
REPORT FILE

NAME: mahima verma


CLASS: XII
ROLL NO.:
SUBJECT: COMPUTER SCIENCE (083)
NAME : SHREYASH TIWARI
SESSION :2019-20
CLASS : XII - C
ROLL NO : 26
SUBJECT : Lab Certificate
COMPUTER SCIENCE (083)
SESSION : 2022-23
SCHOOL : THE LUCKNOW PUBLIC collegiate
LAB CERTIFICATE

This is to certify that Shreyash Tiwari of class XII


has completed this “Report File” under my guidance
and this Report File may be considered as the part
of the practical exam of AISSCE conducted by
CBSE.

Subject teacher:
Mrs. Santwana Srivastava

External Examiner:
_______________________
Acknowledgement
It would be my utmost pleasure to express my
gratitude and sincere thanks to my principal Dr
Jawaid Alam Khan who helped me a lot.
I’m highly indebted to my subject teacher Mrs.
Santwana Srivastava for her guidance and constant
supervision as well as for providing necessary
information regarding this file and also for her help
in completing this Report file.

I would like to express my gratitude towards my


Principal & parents for their kind co-operation and
encouragement.

-Shreyash Tiwari
LIST OF PROGRAMS

1. Write a Python function to find maximum number among given 4 numbers using
list.
2. Write a function to Input any number from user and calculate its factorial.
3. Write a Python function that takes a number as a parameter and check the
number is prime or not.
4. Write a Python function that checks whether a passed string is palindrome or not.
5. Write a function that computes the sum of number 1…...n, get the value of last
number n from the user.
6. Write a function to search an element from a list of integer numbers using binary
search technique.
7. Write a function to search an element from a list of integer numbers using serial
search technique.
8. Write a menu-driven python program using different functions for the following
menu:
1 Check no. is Palindrome or not
2 Check no. is Armstrong or not
3 Exit
9. Write a Program to count the number of words from a text file.
10. Write a program to read content of a text file and display total number of vowels,
consonants, lowercase and uppercase characters
11. Write a program to take details of book from the user and write record in text file.
12. Write a python code to find the size of the file in bytes, number of lines and
number of words.
13. Write a program to read contents of file line by line and display each word
separated by symbol #
14. Write a user-defined function in Python that displays the number of lines starting
with the letter ‘H’ in the file student.txt, if the file contains.
15. Write a program to create a binary file to store Roll no and name, also search for
Roll no and display record if found otherwise display a message "Roll no.
not found"
16. Write a program to perform read and write operation with student .csv file.
17. Write a menu based program to perform operations on stack / implement a stack
using list.
18. WAP to create a stack called Student to perform basic operations on stack using
list. The list contains two data values roll number and name of the student.
Write the following functions:

PUSH()- To add data values into stack


POP()-To remove data values from stack
SHOW()-To display data values from stack
19. Each node of a STACK contains the following information:
(i) Pin code of a city,
(ii) Name of city
Write a program to implement following operations in above stack
(a) Push a node in to the stack.
(b) Remove a node from the stack.
20.Write a program to implement a stack for the employee details (empno, name)
21. a) Consider the following table named ‘EMPLOYEES’ having following
records:

Write SQL queries:


i. To display maximum salary of each job from table EMPLOYEES.
ii. To display minimum salary from table EMPLOYEES.
iii. To count number of records in the table EMPLOYEES.
iv. To show details of all employees those belong job as manager.
v. To display total salary, minimum salary, maximum salary of all managers.
vi. To display the number of EMPLOYEESs in each grade.
vii. To display department number wise total number of jobs and total salary
viii. To display the jobs where the number of EMPLOYEESs is less than 3.
ix. To display the difference of highest and lowest salary of each department
having maximum salary more than 2500.
x. To display the records of the table EMPLOYEES as per the ascending
order of salary.
21.b) SQL Queries:
⮚ Assignment 1. TABLE: ITEM, TABLE: CUSTOMER
⮚ Assignment 2. TABLE: EMPLOYEE, TABLE: SALGRADE
⮚ Assignment 3. TABLE: STOCK, TABLE: DEALERS
⮚ Assignment 4. TABLE: WORKER,TABLE: PAYLEVEL
⮚ Assignment 5. TABLE: SENDER, TABLE: RECIPIENT

22. Write a program to connect Python with MySQL using database connectivity
and perform following operations on data in the database:
a) Create a table
b) insert the data
c) Fetch
d) Update
e) delete the data

23. Write SQL commands/queries to:


a)
i) Create a database named “Information”.
ii) Create a table “Student” in the database” Information” with following
schema/specification:
rollno integer, sname varchar(20), city varchar(10), marks integer and grade char
iii) Enter four records in the table.
b)
i) Write a python program to send SQL command/query to the database to add one
more record:(5.’Manish Agarwal’,’Delhi’,30,’D’).
ii) Write a python program to send SQL command/query to display maximum
marks of the table.
iii) Write a python program send SQL command/query to display number of
students in each grade.
iv) To display the records of the table students as per ascending order of marks.
PROGRAM-1

# Python function to find


# maximum number among given 4 numbers using list

def find_max():
l=[ ]
max1=0
for i in range(4):
n=int(input("Enter number into list:"))
l.append(n)
print("The list is:",l)
for i in l:
if i>max1:
max1=i
print("Max:",max1)
#main
find_max()
OUTPUT
PROGRAM- 2

# Program to calculate factorial of an entered number

def factorial(num):
fact = 1
n = num # storing num in n for printing
while num>1: # loop to iterate from num to 2
fact = fact * num
num-=1

print("Factorial of ", n , " is :",fact)

#main
num = int(input("Enter any number :"))
factorial(num)
OUTPUT
PROGRAM- 3

# Python function that takes a number as a parameter and check the number is prime
or not.

def test_prime(n):
if (n==1):
return False
elif (n==2):
return True
else:
for x in range(2,n):
if(n % x==0):
return False
return True

# main

print(test_prime(11))
OUTPUT
PROGRAM- 4

# Python function that checks whether a passed string is palindrome or not.


def isPalindrome(string):

left_pos = 0

right_pos = len(string) - 1

while right_pos >= left_pos:

if not string[left_pos] == string[right_pos]:

return False

left_pos += 1

right_pos -= 1

return True

print(isPalindrome('madam'))
OUTPUT
PROGRAM- 5

# function to compute sum of numbers from 1 ...n

def compute(num):

s=0

for i in range(1, num+1):

s=s+i

return(s)

#main

n=int(input("Enter any integer : "))

sum=compute(n)

print("The sum of series from 1 to given number is : ", sum)


OUTPUT
PROGRAM- 6
# Function to search an element from a list of integer numbers using binary search
technique.

def binary_search(alist, key):

"""Search key in alist[start... end - 1]."""

start = 0

end = len(alist)

while start <= end:

mid = (start + end)//2

if alist[mid] > key:

end = mid-1

elif alist[mid] < key:

start = mid + 1

else:

return mid

return -1

print("The list is:")

alist=[12,14,16,25,78,89]

print(alist)

key = int(input('The number to search for: '))

index = binary_search(alist, key)

if index < 0:

print('{} was not found.'.format(key))

else:

print('{} was found at index {}.'.format(key, index))


Output
PROGRAM-7
# Program to search an element from a list of integer numbers
# using serial search technique.

def linearSearch(L, n, x):

# Going through List elements sequentially


for i in range(0, n):
if (L[i] == x):
return i
return -1

L = [2, 4, 0, 1, 9]
x = int(input("Enter element to be searched"))
n = len(L)
result = linearSearch(L, n, x)
if(result == -1):
print("Element not found")
else:
print("Element found at index: ", result)
OUTPUT
PROGRAM-8
# Menu-driven python program using different functions

# for the following menu:

# 1 Check no. is Palindrome or not

# 2 Check no. is Armstrong or not

# 3 Exit

# Palindrome

def checkPalin(n):

temp=n

rem=0

rev=0

while(n>0):

rem=n%10

rev=rev*10+rem

n=n//10

if(temp==rev):

print("The number is a palindrome!")

else:

print("The number is not a palindrome!")

# Armstrong

def checkArmstrong(n):

temp=n

rem=0

arm=0
while(n>0):

rem=n%10

arm+=rem**3

n=n//10

if(temp==arm):

print("The number is an armstrong!")

else:

print("The number is not an armstrong!")

def menu():

print("1.Check no. is Palindrome:")

print("2.Check no. is Armstrong:")

print("3.Exit")

opt=int(input("Enter option:"))

no=int(input("Enter number to check:"))

if opt==1:

checkPalin(no)

elif opt==2:

checkArmstrong(no)

elif opt==3:

sys.exit()

else:

print("Invalid option")

# main

menu()
OUTPUT
PROGRAM- 9

# Program to count the number of words from a text file

fin=open(r"C:\Users\my\Desktop\new.txt",'r')

str=fin.read( )

L=str.split()

count_words=0

for i in L:

count_words=count_words+1

print("number of words are:",count_words)


File new.txt :
OUTPUT
PROGRAM- 10
#Program to read content of file
#and display total number of vowels, consonants, lowercase and uppercase
characters

f = open(r"C:\Users\Administrator\Desktop\file1.txt")
v=0
c=0
u=0
l=0
o=0
data = f.read()
vowels=['a','e','i','o','u']
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
o+=1
print("Total Vowels in file:",v)
print("Total Consonants in file n :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
print("Total Other than letters :",o)
f.close()
file1.txt :
OUTPUT
PROGRAM-11
# Program to take the details of book from the user and

# write the records in text file.

fout =open("D:\\Book.txt",'w')

n=int(input("How many records you want to write in a file ? :"))

for i in range(n):

print("Enter details of record :", i+1)

title=input("Enter the title of book : ")

price=float(input("Enter price of the book: "))

record=title+" , "+str(price)+'\n'

fout.write(record)

fout.close( )
OUTPUT
PROGRAM-12
# Python code to find the size of the file in bytes, number of lines and number of
words.

f=open(r"C:\Users\my\Desktop\project.txt","r")

word=0

ln=0

str=f.read( )

size=len(str)

print("size of file n bytes",size)

f.seek(0)

while True:

line=f.readline() #Read a line

if not line:

break # Enocounter EOF

else:

ln=ln+1 #Count number of line

string=line.split()

length=len(string)

word=word+length

print("Number of lines ",ln)

print("Number of words ",word)

f.close( )
File: project.txt
OUTPUT
PROGRAM-13
# Program to read content of file line by line

# and display each word separated by #

f = open(r"C:\Users\Administrator\Desktop\w_display.txt")

for line in f:

words = line.split()

for w in words:

print(w+'#',end='')

print()

f.close()

NOTE : if the original content of file is:

India is my country

We are Indians

I love my country
PROGRAM-14
# A user-defined function in Python that displays the number of lines starting with
the letter ‘H’ in the file student.txt, if the file contains.

def count_H():

f=open(r"C:\Users\my\Desktop\ student.txt ","r")

data=f.readlines( )

count_H=0

for i in data:

if i[0]=='H':

count_H += 1

print("Total number of lines starting with H present : ",count_H)

#main

count_H( )
File : student.txt
OUTPUT
PROGRAM-15
# Program to create a binary file to store Rollno and name

# Search for Rollno and display record if found

# otherwise "Roll no. not found"

import pickle

student=[]

f=open('student.dat','wb')

ans='y'

while ans.lower()=='y':

roll = int(input("Enter Roll Number :"))

name = input("Enter Name :")

student.append([roll,name])

ans=input("Add More ?(Y)")

pickle.dump(student,f)

f.close()

# to read

f=open('student.dat','rb')

student=[]

while True:

try:

student = pickle.load(f)

except EOFError:

break
ans='y'

while ans.lower()=='y':

found=False

r = int(input("Enter Roll number to search :"))

for s in student:

if s[0]==r:

print("## Name is :",s[1], " ##")

found=True

break

if not found:

print("####Sorry! Roll number not found ####")

ans=input("Search more ?(Y) :")

f.close()
OUTPUT
PROGRAM-16
# Write a program to perform read and write operation with student.csv file.

import csv

def readcsv():

with open(r'C:\Users\Administrator\Desktop\ student.csv','r', newline='\n') as


f:

data=csv.reader(f) #reader function to generate a reader object

for row in data:

print(row)

def writecsv( ):

with open(r'C:\Users\Administrator\Desktop \student.csv', mode='a',


newline='') as file:

writer = csv.writer(file, delimiter=' ,' , quotechar='"')

#write new record in file

writer.writerow(['4', 'sruesh', 'Arts', '404'])

print("Press-1 to Read Data: ")

print("Press-2 to Write data: ")

a=int(input())

if a==1:

readcsv()

elif a==2:

writecsv()

else:

print("Invalid value")
OUTPUT
PROGRAM-17
# Menu based program to perform operations on stack / implement a stack using
list.

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 isEmpty(stk):

return "underflow"

else:

item=stk.pop()

if len(stk)==0:

top=None

else:

top=len(stk)-1

return item

def topvalue(stk):

if isEmpty(stk):

return "underflow"

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=[]

top=None

while True:

print("STACK OPERATION")

print(" 1. Push ")

print(" 2. Pop ")

print(" 3. Top ")

print(" 4. Display")

print(" 5. Exit ")

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

if ch==1:

item=input("Enter the element: ")

push(stack,item)
elif ch==2:

item=pop(stack)

if item=="underflow":

print("Stack is empty")

else:

print("Deleted element is :",item)

elif ch==3:

item=topvalue(stack)

if item=="underflow":

print("underflow!stack is empty!")

else:

print("top most item is",item)

elif ch==4:

display(stack)

elif ch==5:

break

print("invalid choice")
OUTPUT
PROGRAM-18

""" Program to create a stack called Student to perform basic operation on stack
using list. The list contains two data values roll number and name of student.
following functions:
PUSH()- To add data values into stack
POP()-To remove data values from stack
SHOW()-To display data values from stack"""

Student=list() # A default stack


top=-1 # To know the current index position
# TO ADD ELEMENT
def PUSH(Student,top):
ch='Y'
while ch=='Y' or ch=='y' or ch=='yes':
Rollno=int(input("enter the roll number :"))
Name=input("enter the name :")
std=(Rollno,Name) # Creating a list
Student.append(std)
top=len(Student)-1
print("Do you want to add more...<y/n>")
ch=input()
if ch=='N' or ch=='n':
break
return top
# TO REMOVE STACK ELEMENTS
def POP(Student,top):
slen=len(Student)
if slen<=0:
print("Stack is empty")
else:
Rollno,Name=Student.pop()
top=len(Student)-1
print("Value deleted from stack is",Rollno,Name)
return top
# SHOWING STACK ELEMENTS
def SHOW(Student,top):
slen=len(Student)
if slen<=0:
print("Stack is empty")
else:
print("The list elements are...")
i=top
while (i>=0):
Rollno,Name=Student[i]
print(Rollno,Name)
i-=1
while True:
print()
print('STACK OPERATION')
print('---------------')
print('1.Add Student Data')
print('2.Remove Student Data')
print('3.Display Student Data')
print('4.Stop operation')
Opt=int(input("Enter your option:"))
if Opt==1:
top=PUSH(Student,top)
elif Opt==2:
top=POP(Student,top)
elif Opt==3:
SHOW(Student,top)
else:
break
OUTPUT
PROGRAM-19
# Program to perform push(insert pin code and city) and pop(remove pin code and
city) operations in the stack

stack = [ ]

while True :

print()

print("Enter your choice as per given -")

print("1 = For insert data Enter insert ")

print("2 = For delete data enter delete ")

print("3 = For Exit enter exit ")

print()

user = input("Enter your choice :- ")

if user == "insert" :

pin = int(input("Enter the pin code of city :- "))

city = input("Enter name of city :- ")

data = [ pin , city ]

stack.append(data)

elif user == "delete" :

if stack == [ ]:

print("Under Flow")

else :

print(stack.pop())

else :

break
OUTPUT
PROGRAM-20
# Program to implement a stack for the employee details ( empno, name)
def push():
empno=int(input("Enter the employee number to push:"))
ename=input("Enter the employee name to push:")
stk.append([empno,ename])
global top
top=len(stk)-1

def display():
global top
if top==-1:
print("Stack is Empty")
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[i])

def pop_ele():
global top
if top==-1:
print("Stack is Empty")
else:
print(stk.pop())
top=top-1
#main
stk=[]
top=-1
while True:
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
ch=int(input("Enter your choice:"))
if ch==1:
push()
print("Element Pushed")
elif ch==2:
pop_ele()
elif ch==3:
display()
elif:
break
else:
print("Invalid Choice")
OUTPUT
Question 21
a) Consider the following table named ‘EMPLOYEES’ and write SQL Queries:

i. To display the maximum salary from table EMPLOYEES grouped by job.

Ans. SELECT JOB, MAX(SAL) FROM EMPLOYEES GROUP BY JOB;

ii. To display the minimum salary from table EMPLOYEES.

Ans:-SELECT MIN(SAL) FROM EMPLOYEES;


iii. To count number of records in the table EMPLOYEES.
Ans:- SELECT COUNT(*) “Total number” FROM EMPLOYEES;

iv. To show details of all employees those belong job as manager.


Ans:- SELECT * FROM EMPLOYEES WHERE JOB='MANAGER';

v. To display total salary, minimum salary, maximum salary of all the


managers.

Ans:- SELECT SUM(SAL)'TOTAL SALARY', MIN(SAL)'MINIMUM


SAL',MAX(SAL)'MAXIMUM SAL',AVG(SAL)'AVG. SAL' FROM EMPLOYEES
WHERE JOB='MANAGER';

vi. To display the number of EMPLOYEESs in each grade.

Ans:- SELECT JOB,COUNT(*) FROM EMPLOYEES GROUP BY JOB;


vii. To display department number wise total number of jobs and total salary

Ans:-SELECT DEPTNO,COUNT(*),SUM(SAL) FROM EMPLOYEES GROUP BY


DEPTNO;

viii. To display the jobs where the number of EMPLOYEESs is less than 3.
Ans:-SELECT JOB,COUNT(*) FROM EMPLOYEES GROUP BY JOB HAVING
COUNT(*) < 3;

ix. To display the difference of highest and lowest salary of each department
having maximum salary more than 2500.
Ans:-SELECT MAX(SAL) - MIN(SAL)'DIFFERENCE' FROM EMPLOYEES
GROUP BY DEPTNO HAVING MAX(SAL) > 2500;
x. To display the records of the table EMPLOYEES as per the ascending
order of salary.

Ans:- SELECT * FROM EMPLOYEES ORDER BY SAL ASC;


21. b) Assignment 1. TABLE: ITEM, TABLE: CUSTOMER

ITEM
-------------------------------------------------------------------------------------------------------------------
I_ID ITEMNAME MANUFACTURER PRICE
------------------------------------------------------------------------------------------------------- -----------------
PC01 PERSONAL COMPUTER ABC 35000
LC05 LAPTOP ABC 55000
PC03 PERSONAL COMPUTER XYZ 32000
PC06 PERSONAL COMPUTER COMP 37000
LC03 LAPTOP PQR 57000
-------------------------------------------------------------------------------------------------------------------
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 AGARWAL BANGALORE PC01
-------------------------------------------------------------------------------------------------------------------
Questions :

1) Display details of those Customers whose city is Delhi.

2) Display details of items whose price is in the range of 35000 to 50000.

3) Display the customer name, city from table CUSTOMER and Item Name and Price from

table ITEM with their corresponding matching I_ID.

4) Increase the price of all items by 1000 in the table ITEM.

5) Display distinct City name from table customer.

ASSIGNMENT 1
Ans 1) SELECT * FROM CUSTOMER WHERE CITY=’DELHI’;
C_ID CUSTOMERNAME CITY I_ID
------- --------------------------------------------- ---------- -----
1 N ROY DELHI LC03
12 R PANDEY DELHI PC06
15 C SHARMA DELHI LC03

Ans 2) SELECT * FROM ITEM WHERE PRICE BETWEEN 35000 AND 55000;
I_ID ITEMNAME MANUFACTURER PRICE
---------- ----------------------------------- ---------------------------- -----------
PC01 PERSONAL COMPUTER ABC 35000
LC05 LAPTOP ABC 55000
PC06 PERSONAL COMPUTER COMP 37000
Ans 3) SELECT A.CUSTOMERNAME, A.CITY, B.ITEMNAME, B.PRICE FROM
CUSTOMER A, ITEM B WHERE A.I_ID= B.I_ID;

CUSTOMERNAME CITY ITEMNAME PRICE


-------------- ---------- -------------------- ----------
K AGARWAL BANGALORE PERSONAL COMPUTER 35000
H SINGH MUMBAI PERSONAL COMPUTER 32000
R PANDEY DELHI PERSONAL COMPUTER 37000
C SHARMA DELHI LAPTOP 57000
N ROY DELHI LAPTOP 57000

Ans 4) UPDATE ITEM


SET PRICE=PRICE+1000;
5 rows updated

Ans 5) SELECT DISTINCT(CITY) FROM CUSTOMER;

CITY
----------
MUMBAI
BANGLORE
DELHI
⮚ Assignment 2. TABLE: EMPLOYEE, TABLE: SALGRADE

EMPLOYEE

ECODE NAME DESIG SGRADE DOJ DOB


------------- ------------- ------------- ------------ ------------- -----------
101 ABDUL AHMAD EXECUTIVE S03 23-MAR-2003 13-JAN-1980
102 RAVI CHANDER HEAD-IT S03 23-MAR-2010 22-JAN-1980
103 JOHN KEN RECEPTIONIST S03 24-JUN-2009 24-FEB-1983
105 NAZAR AMEEN GM S02 24-JAN-2006 03-MAR-1984
109 PRIYAM SEN CEO S01 29-DEC-2004 19-JAN-1982

SALGRADE
SGRADE SALARY HRA
-------------- ------------ -----------
S02 32000 12000
S03 24000 8000
S01 56000 18000
Questions:

1) Display NAME and DESIG of those EMOLOYEEs, whose SALGRADE is either


S02 or S03.

2) Display the details of all Employees in descending order of DOJ.

3) Display the minimum DOB and maximum DOJ.

4) Display ECODE and NAME of those employees whose SGRADE is more than or
equal to ‘S03’.

5) Display sgrade from table SALGRADE of those employees whose SALARY +HRA
is more than 40000.
ASSIGNMENT : 2

Ans 1) SELECT NAME, DESIG FROM EMPLOYEE

WHERE (SGRADE =’S02’ OR SGRADE=’S03’);

NAME DESIG
----------------------------------- ----------------------
ABDUL AHMAD EXECUTIVE
RAVI CHANDER HEAD-IT
JOHN KEN RECEPIONIST
NAZAR AMEEN GM

Ans 2) SELECT * FROM EMPLOYEE ORDER BY DOJ DESC;

ECODE NAME DESIG SGRADE DOJ DOB


------- -------------------- - ------------------- ----------- --------- ---------
102 RAVI CHANDER HEAD-IT S03 23-MAR-10 22-JAN-80
103 JOHN KEN RECEPTIONIST S03 24-JUN-09 24-FEB-83
105 NAZAR AMEEN GM S02 24-JAN-06 03-MAR-84
109 PRIYAM SEN CE0 S01 29-DEC-04 19-JAN-82
101 ABDUL AHMAD EXECUTIVE S03 23-MAR-03 13-JAN-80

Ans 3) SELECT MIN(DOB),MAX(DOJ) FROM EMPLOYEE;

MIN(DOB) MAX(DOJ)
--------------- ---------------
13-JAN-1980 23-MAR-2010

Ans 4) SELECT ECODE, NAME FROM EMPLOYEE WHERE SGRADE>='S03';

ECODE NAME
--------------- ---------------------------------
101 ABDUL AHMAD
102 RAVI CHANDER
103 JOHN KEN

Ans 5) SELECT SGRADE FROM SALGRADE WHERE SALARY+HRA>=40000;


SGRADE
-------------
S02
S01
⮚ Assignment 3. TABLE: STOCK, TABLE: DEALERS

STOCK

ITEMNO ITEM DCODE QTY RATE LASTBUY

-------- -------------------- ---------- ---------- ---------- ------------

5005 BALL PEN 0.5 102 100 16 31-MAR-10

5003 BALL PEN 0.25 102 150 20 01-JAN-10

5002 GEL PEN PREMIUM 101 125 14 14-FEB-10

5006 GEL PEN CLASSIC 101 200 22 01-JAN-09

5001 ERASER SMALL 102 210 5 19-MAR-09

5004 ERASER BIG 102 60 10 12-DEC-09

5009 SHARPENER CLAS 103 160 8 23-JAN-09

DEALERS

DCODE DNAME

------------- --------------------

101 RELIABLE STATIONERS

103 CLASSIC PLASTICS

102 CLEAR DEALS

Questions-

(1) Display details of all Items in the STOCK table where LASTBUY date is after 14-FEB-10.

(2) Display ITEMNO and Item Name of those ITEM from STOCK Table whose RATE is more than
Rupees 14 and ITEMNO is either 5005 or 5006.

(3) Display ITEMNO, ITEM of those items whose dealer code (DCODE) is 101 or Quantity in Stock
(QTY) is more than 160 from the table STOCK.

(4) Display Maximum RATE of Items for each dealer individually as per DCODE from the table
Stock.

(5) Count distinct DCODE from the table DEALERS.


ASSIGNMENT 3:
Ans 1) SELECT * FROM STOCK WHERE LASTBUY >'14-FEB-10';

ITEMNO ITEM DCODE QTY RATE LASTBUY


----------- ------------------ ---------------- ---------- ---------- ---------------
5005 BALL PEN 0.5 102 100 16 31-MAR-10

Ans 2) SELECT ITEMNO, ITEM FROM STOCK WHERE RATE >14 AND ITEMNO =5005
OR ITEMNO=5006;

ITEMNO ITEM
------------------- --------------------
5005 BALL PEN 0.5
5006 GEL PEN CLASSIC

Ans 3) SELECT ITEMNO, ITEM FROM STOCK WHERE DCODE = 101 OR QTY > 160;

ITEMNO ITEM
--------------- --------------------
5002 GEL PEN PREMIUM
5006 GEL PEN CLASSIC
5001 ERASER SMALL

Ans 4) SELECT DCODE, MAX(RATE) FROM STOCK GROUP BY DCODE;

DCODE MAX(RATE)
-------------- -------------------
102 20
101 22
103 8

Ans 5) SELECT COUNT(DISTINCT DCODE) FROM DEALERS;

COUNT(DISTINCT DCODE)
-------------------------------
3
Assignment 4. TABLE: WORKER,TABLE: PAYLEVEL
WORKER

ECODE NAME DESIGN PLEVEL DOJ DOB

------------ ----------------- ---------------- --------------- ------------- ------------

11 Radhey Shyam Supervisor P001 13-Sep-2004 23-Aug-1981

12 Chander Nath Operator P003 22-Feb-2010 12-Jul-1987

13 Fizza Operator P003 14-Jun-2009 14-Oct-1983

14 Ameen Ahmed Mechanic P002 21-Aug-2006 13-Mar-1984

18 Sanya Clerk P002 19-Dec-2005 09-Jun-1983

PAYLEVEL

PLEVEL PAY ALLOWANCE

-------------- --------- -----------------------

P001 26000 12000

P002 22000 10000

P003 12000 6000

Questions-

1.) Display the details of all WORKERs in descending order of DOB.

2.) Display NAME and DESIG of those WORKERs, whose PLEVEL is either P001 or P002.

3.) Display the content of all the Workers, where DESIG is Operator.

4.) To display maximum DOB and Minimum DOJ from the table WORKER.

5.) To add a new row with the following:

19,’Daya Kishore’,’Operator’,’P003’,19-Jun-2008’,’11-Jul-1984’.
ASSIGNMENT 4:
Ans 1) SELECT * FROM WORKER ORDER BY DOB DESC;

ECODE NAME DESIGN PLEVEL DOJ DOB


----------- -------------------- --------------- --------------- ------------ --------------------
12 Chander Nath Operator P003 22-FEB-10 12-JUL-87
14 Ameen Ahmed Mechanic P002 21-AUG-06 13-MAR-84
13 Fizza Operator P003 14-JUN-09 14-OCT-83
18 Sanya Clerk P002 19-DEC-05 09-JUN-83
11 Radhey Shyam Supervisor P001 13-SEP-04 23-AUG-81

Ans 2) SELECT NAME, DESIG FROM WORKER WHERE PLEVEL IN(‘P001’,’P002’);

NAME DESIGN
------------- --------------
Radhey Shyam Supervisor
Ameen Ahmed Mechanic
Sanya Clerk

Ans 3) SELECT * FROM WORKER WHERE DESIGN=’Operator’;

ECODE NAME DESIGN PLEVEL DOJ DOB


--------- ------------- ----------- ------------ ---------- -----------
12 Chander Nath Operator P003 22-Feb-2010 12-Jul-1987
13 Fizza Operator P003 14-Jun-2009 14-Oct-1983

Ans 4) SELECT MAX(DOB), MIN(DOJ) FROM WORKER;

MAX(DOB) MIN(DOJ)
--------------- --------------
12-JUL-1987 13-SEP-2004

Ans 5) INSERT INTO WORKER


VALUES(19, ’Daya Kishore’,’Operator’,’P003’,’19-Jun-2008’,’11-Jul-1984’);
1 row created.
ASSIGNMENT : 5 TABLE: SENDER, TABLE: RECIPIENT
SENDER
-----------------------------------------------------------------------------------------------------------------
SENDER_ID SENDER_NAME SENDER_ADDRESS SENDER_CITY
-----------------------------------------------------------------------------------------------------------------
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
-----------------------------------------------------------------------------------------------------------------

RECIPIENT
---------------------------------------------------------- ----------------------------------------------------------------
REC_ID SENDER_ID REC_NAME REC_ADDRESS REC_CITY
-----------------------------------------------------------------------------------------------------------------
KO05 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 P K SWAMY B5,C S TERMINUS MUMBAI
ND48 ND50 S TRIPATHI 13,B1 D,MAYURVIHAR NEW DELHI
----------------------------------------------------------------------------------------------------------------------------
Questions-
a) Display the names of all Senders from Mumbai.

b) Display REC_ID, REC_NAME of those RECIPIENT whose SENDER_ID is either

‘MU02’ or ‘ND50’

c) Display recipient details in ascending order of RECNAME.

d) Display number of recipients from each city.

e) Display distinct Sender City from the table SENDER.


ASSIGNMENT 5
Ans 1) SELECT SENDER_NAME FROM SENDER WHERE SENDER_CITY = 'MUMBAI';
SENDER_NAME
---------------------
H SINHA
S JHA
Ans 2) SELECT REC_ID, REC_NAME FROM RECIPIENT WHERE SENDER_ID ='MU02' OR

SENDER_ID = 'ND50';

REC_ID REC_NAME

------------- --------------------

ND08 S MAHAJAN

ND48 STRIPATHI

Ans 3) SELECT * FROM RECIPIENT ORDER BY REC_NAME;

REC_ID SENDER_ID REC_NAME REC_ADDRESS REC_CITY


---------- --------------- --------------------- -------------------- -------------
MU19 ND01 H SINGH 2A,ANDHERI EAST MUMBAI
MU32 MU15 P K SWAMY B5,C S TERMINUS MUMBAI
K005 ND01 R BAJPAYEE 5,CENTRAL AVENUE KOLKATA
ND08 MU02 S MAHAJAN 116,A VIHAR NEW DELHI
ND48 ND50 S TRIPATHI 13,B1 D,MAYUR VIHAR NEW DELHI

Ans 4) SELECT REC_CITY, COUNT(*) FROM RECIPIENT GROUP BY REC_CITY;

REC_CITY COUNT(*)
--------------- -----------------
KOLKATA 1
MUMBAI 2
NEW DELHI 2

Ans 5) SELECT DISTINCT SENDER_CITY FROM SENDER;

SENDER_CITY
--------------------
MUMBAI
NEW DELHI
PROGRAM- 22
# Write a Python program to connect with MySQL using database connectivity and
perform the following operations on data in the database:
a) Create a table
b) insert the data
c) Fetch
d) Update
e) delete the data
a) Create a table

# Python program to create a table


import mysql.connector
path=mysql.connector.connect(host="localhost",user="root",passwd="admin",dat
abase="project")
cursor=path.cursor()
cursor.execute("CREATE TABLE STUDENTS(ROLL INT,SNAME VARCHAR(30),CLASS
INT,CITY VARCHAR(20))")
print("The created Table is STUDENTS")
cursor.execute("DESCRIBE STUDENTS")
for x in cursor:
print(x)
path.close()
cursor.close()

OUTPUT
b) insert the data
import mysql.connector
path=mysql.connector.connect(host="localhost",user="root",passwd="admin",
database="project")
cursor=path.cursor()
sql="INSERT INTO
STUDENTS(ROLL,SNAME,CLASS,CITY)VALUES({},'{}',{},'{}')".format(4,"ROHIT",11,
"DELHI")
cursor.execute(sql)
path.commit()
cursor.execute("SELECT* FROM STUDENTS")
print("The inserted data is :")
data=cursor.fetchall()
for x in data:
print(x)
cursor.close()
path.close()

OUTPUT
C) Fetch

import mysql.connector

path=mysql.connector.connect(host="localhost",user="root",passwd="admin",
database="project")

cursor=path.cursor()

cursor.execute("SELECT * FROM STUDENTS")

data=cursor.fetchall()

print("Data featched from table is-:")

for x in data:

print(x)

path.close()

cursor.close()

OUTPUT
d) Update

import mysql.connector

path=mysql.connector.connect(host="localhost",user="root",passwd="admin",
database="project")

cursor=path.cursor()

sql="UPDATE STUDENTS SET class =11 WHERE class=12"

cursor.execute(sql)

path.commit()

cursor.execute("SELECT *FROM STUDENTS")

data=cursor.fetchall()

for x in data:

print(x)

path.close()

cursor.close()

OUTPUT
e) delete

import mysql.connector
path=mysql.connector.connect(host="localhost",user="root",passwd="admin",
database="project")
cursor=path.cursor()
sql="DELETE FROM STUDENTS WHERE ROLL=2"
cursor.execute(sql)
path.commit()
cursor.execute("SELECT *FROM STUDENTS")
data=cursor.fetchall()
print("Data left in the table-:")
for x in data:
print(x)
path.close()
cursor()

OUTPUT
QUESTION -23

# Write SQL commands/queries to:


a)
i) Create a database named “Information”.

CREATE DATABASE INFORMATION;


OUTPUT

ii) Create a table “Student” in the database” Information” with following schema/specification:

(rno integer, sname varchar(20), city varchar(10), marks integer and grade char )

CREATE TABLE STUDENTS


(
RNO INT,
SNAME VARCHAR(20),
CITY VARCHAR(10),
MARKS INT,
GRADE CHAR(5) );
OUTPUT
iii) Enter four records in the table.

INSERT INTO STUDENTS

VALUES(1,'RAKESH','MUMBAI',35,'C'),(2,'ROHIT','DELHI',40,'B'),(3,'YOGENDRA','BANARAS',35,'C'),
(4,'MUDIT','LUCKNOW',50,'A');

OUTPUT
b)

i) Write a python program to send SQL command/query to the database to add


one more record:(5,’Manish Agarwal’,’Delhi’,30,’D’) in the table students.

import mysql.connector
path=mysql.connector.connect(host="localhost",user="root",passwd="admin",
database="information")
cursor=path.cursor()
sql="INSERT INTO
students(RNO,SNAME,CITY,MARKS,GRADE)values({},'{}','{}',{},'{}')".format(5,'Mohit
Agrawal','Pune',40,'C')
cursor.execute(sql)
path.commit()
# to check records
cursor.execute(" SELECT* FROM students")
print("The inserted data is :")
data=cursor.fetchall()
for a in data:
print(a)
path.close()
cursor.close()
OUTPUT
ii) Write a python program to send SQL command/query to display maximum
marks of the table.

import mysql.connector

path=mysql.connector.connect(host="localhost",user="root",passwd="admin",dat
abase="information")

cursor=path.cursor()

cursor.execute("SELECT MAX(MARKS) FROM students")

for d in cursor:

print(d)

path.close()

cursor.close()

OUTPUT
iii) Write a python program send SQL command/query to display number of
students in each grade.

import mysql.connector

path=mysql.connector.connect(host="localhost",user="root",passwd="admin",
database="information")

cursor=path.cursor()

sql="SELECT GRADE, count(sname) FROM students GROUP BY GRADE"

cursor.execute(sql)

data=cursor.fetchall()

for a in data:

print(a)

path.close()

cursor.close()

OUTPUT
iv) To display the records of the table students as per ascending order of marks.

import mysql.connector

path=mysql.connector.connect(host="localhost",user="root",passwd="admin",dat
abase="information")

cursor=path.cursor()

sql="SELECT * FROM students ORDER BY marks ASC"

cursor.execute(sql)

data=cursor.fetchall()

for a in data:

print(a)

path.close()

cursor.close()

OUTPUT
Bibliography

● Computer science with python by Sumita


Arora for class 12.

• Computer science : Saraswati


publication.

You might also like