Professional Documents
Culture Documents
PRACTICAL FILE
COMPUTER SCIENCE
SUBJECT CODE- 083
AISSCE 2023-2024
__________________________
Class 12
KV ONGC RAJAHMUNDRY,
CERTIFICATE
This is to certify that the Computer Science (083) Practical File has been
successfully completed by ______________________________ of Class XII, KV
ONGC RAJAHMUNDRY School for consideration in partial fulfillment of
curriculum of Central Board of Secondary Education (CBSE) of Computer
Science (083) for the award of AISSCE Practical Examination 2023-24.
____________________ ___________________
(Examiner) (Principal)
ACKNOWLEDGEMENT
I would also thank all of my parents and friends for their whole
hearted support and encouragement without with this project would not
have been successful.
Features of Python:
Python programs are easy to understand as they have a clearly defined syntax
andrelatively simple structure.
Python is case-sensitive. For example, NUMBER and number are not same in
Python.
Characteristics of MySQL:
● Windows, UNIX, LINUX etc. and have compatibility with many languages
includingJAVA, C++, PHP, PERL, etc.
● MySQL is an easy to install RDBMS and is capable of handling large data sets.
Since MySQL is released under an open-source license, it does not require any cost or
payment for its usage. Anyone can download and use this software from specific
location on Internet.
SYSTEM REQUIREMENT AND SPECIFICATIONS
Software Requirements:
Hardware Requirements:
Input/output Requirements:
Source Code:
import random
while True:
Choice=input ("\nDo you want to roll the dice (y/n) : ")
no=random. randint (1, 6)
if Choice == 'y' :
print ("\nYour Number is:", no)
else:
break
Output:
# Practical No. 2 - Write a program in Python language to count the
# total number of characters "A" or "a" present in data file LINES.TXT.
c=0
f=open("LINES.TXT","r")
rec=f.read()
l=len(rec)
for i in range(0,l,1):
if(rec[i]=='A' or rec[i]=='a'):
c=c+1;
print("Total count of A or a is = ",c)
f.close()
#Practical No. 3 - Write a Python Program to read a text file "Story.txt" and displays the number of Vowels/
Consonants/ Lowercase / Uppercase characters in the file.
Source Code:
f=open("Story.txt",'r')
Contents=f.read()
Vowels=0
Consonants=0
Lowercase=0
Uppercase=0
for ch in Contents:
if ch in 'aeiouAEIOU':
Vowels=Vowels+1
if ch in 'bedfghjklmmperstvwxyzBCDFGHJKLMNPORSTVWXYZ':
Consonants=Consonants+1
if ch.islower():
Lowercase=Lowercase+1
if ch.isupper():
Uppercase=Uppercase+1
f.close()
print("The total numbers of vowels in the file: ",Vowels)
print("The total numbers of consonants is the file: ",Consonants)
print("The total numbers of uppercase in the file: ",Uppercase)
print("The total numbers of lowercase in the file: ",Lowercase)
Content of story.txt :
Like a Joy on the heart of a sorrow.
The sunset hangs on a cloud.
# Practical No.4 - Write a program using data file concepts to read the contents of
# a data file "LINES.TXT" and display the total count of Lowercase Characters,
# Uppercase Characters, Digits and No. of Special Characters present in this file.
uc=0
lc=0
d=0
sp=0
f=open("LINES.TXT","r")
rec=f.read()
l=len(rec)
for i in range(0,l,1):
if (rec[i].islower()):
lc=lc+1
elif (rec[i].isupper()):
uc=uc+1
elif (rec[i].isdigit()):
d=d+1
else:
sp=sp+1
print(" No. of Lowercase Characters=",lc)
print(" No. of Uppercase Characters=",uc)
print(" No. of Digits=",d)
print(" No. of Special Characters=",sp)
f.close()
#Practical No.-5 Write a program in python language to read the contents of a
#text file "LINES.TXT" and display the count of "THE" and "IS" in the data file.
c=0
d=0
f=open("LINES.TXT","r")
rec=f.read()
words=rec.split(" ")
l=len(words)
for i in range(0,l,1):
if(words[i].upper()=="THE"):
c=c+1
elif(words[i].upper()=="IS"):
d=d+1
print("Total count of the =",c)
print("Total count of is =",d)
print("Total count of the and is =",(c+d))
f.close()
#Practical No.-6 Write a program in python language to read the contents of a
#text file "LINES.TXT" and display the total number of words in the data file.
f=open("LINES.TXT","r")
rec=f.read()
words=rec.split(" ")
l=len(words)
print("Total words = ",l)
f.close()
#Practical No.-7 Write a program in python language to read the contents of a
#text file "LINES.TXT" and display the total number of lines in the data file.
c=0
f=open("LINES.TXT","r")
rec=f.readline()
while rec:
c=c+1
rec=f.readline()
Source Code:
f=open ("Story.txt",'r')
Contents=f.readlines()
for line in Contents:
words=line.split()
for i in words:
print(i+'#',end=' ')
print("")
f.close ()
Content of story.txt :
Like a Joy on the heart of a sorrow.
The sunset hangs on a cloud.
#Practical No. 9 - To write a python program to read lines from a text file "Sample.txt" and copy those lines into
another file which are starting with an alphabet 'a' or 'A'.
Program :
#Program No. - To write a python program to read lines from a text file "Sample.txt"
# and copy those lines into another file which are starting with an alphabet 'a' or 'A'.
F1=open("Sample.txt",'r')
F2=open("New.txt",'w')
while True:
line=F1.readline()
if line == '' :
break
if line [0] == 'a' or line[0] == 'A':
F2.write(line)
print("All lines which are starting with character 'a' or 'A' has been copied successfully into New.txt")
F1. close ()
F2. close ()
Content of story.txt :
Aeroplane was invented by the Right Brothers.
My favorite color is skyblue.
An apple a day keeps the doctor away.
Output:
Content of new.txt :
#Practical No. 10 - Write a Python Program to create a binary file with roll number and name. Search for a given
roll number and display the name, if not found display appropriate message.
Source Code :
#Write a Python Program to create a binary file with roll number and name.
#Search for a given roll number and display the name, if not found display
#appropriate message.
import pickle
def Create():
F=open ("Students.dat",'ab')
opt='y'
while opt == 'y' or opt=='Y':
RollNo=int(input('Enter roll number: '))
Name=input("Enter Name: ")
L=[RollNo,Name]
pickle.dump(L,F)
opt=input("Do you want to add another student detail (y/n) :")
F.close()
def Search():
F=open("Students.dat",'rb')
no=int(input("Enter Roll. No of student to search:"))
found=0
try:
while True:
S=pickle.load(F)
if S[0]==no:
print("The searched Roll. No is found and Details are:",S)
found=1
break
except:
F.close()
if found==0:
print("The Searched Roll. No is not found")
#Main Program
Create()
Search()
Output:
#Practical No. 11 - Write a Python Program to create/store content in a binary
# file “Marks.dat” with roll number, name, mark and update/modify the mark for
# a given roll number if it is present, otherwise display appropriate message.
Source Code:
import pickle
def Create():
F=open("Marks.dat",'ab')
opt='y'
F.close ()
def Update () :
F=open("Marks.dat",'rb+')
no=int(input("Enter Student Roll. No to modify marks: "))
found=0
try:
while True:
Pos=F.tell()
S=pickle.load(F)
if S[0]==no:
print ("The searched Roll. No is found and Details are: ",S)
S[2]=int(input("Enter New Mark to be update: "))
F.seek(Pos)
pickle.dump(S,F)
found=1
F.seek(Pos) #moving the file pointer again beginning of the current record
print("Mark updated Successfully and Details are:",S)
break
except:
F. close ( )
if found==0:
print("The Searched Roll No is not found")
#Main Program
Create()
Update()
Output:
#Practical No. 12 – Write a Python Program to create/store content in a binary
# file “emp.dat” with empno, name, post and salary, display sum of salaries for
# the given post.
import pickle
def NewEmp():
print("Enter the details of an employee : ")
no=int(input("Enter the Empno ? "))
name=input("Enter the name ? ")
post=input("Enter the post ? ")
sal=float(input("Enter the salary ? "))
rec=[no,name,post,sal]
f=open("EMP.dat","ab")
pickle.dump(rec,f)
print("New record saved")
f.close()
def SumSalary(Post):
f=open("EMP.dat","rb")
c=0
sum=0
try:
while True:
rec=pickle.load(f)
if rec[2]==Post:
sum+=rec[3]
except EOFError:
f.close()
Output:
#Practical No. 13 - Write a Python program to create a CSV file to store Empno, Name, Salary and search any
Empno and display Name, Salary and if not found display appropriate message.
Source Code:
#Program No. - Write a Python Program to Create a binary file with roll number, name, mark
#and update/modify the mark for a given roll number.
import csv
def Create():
F=open ("Emp.csv",'a', newline='')
W=csv.writer(F)
opt= 'y'
while opt=='y' or opt=='Y' :
No=int(input("Enter Employee Number: "))
Name=input("Enter Employee Name: ")
Sal=float(input ("Enter Employee Salary: "))
L=[No,Name,Sal]
W.writerow(L)
opt=input("Do you want to continue (y/n) ?")
F.close()
def Search():
F=open("Emp.csv",'r',newline='\r\n')
no=int(input("Enter Employee number to search : "))
found=0
row=csv.reader(F)
for data in row:
if data[0] == str(no) :
print("\nEmployee Deatils are:")
print(" ----------------------")
print("Name : ",data[1])
print("Salary: ",data[2])
print("-----------------------")
found=1
break
if found == 0:
print ("The searched Employee number is not Found")
F. close ()
#Main Program
Create ()
Search ()
Output:
#Program No. 14- Write a Python Program to create a CSV file with employee number, name and salary.
#Search for given employee number and if the given employee number is present display its
#name and salary otherwise give appropriate message.
import csv
def Create():
F=open ("Emp.csv",'a', newline='')
W=csv.writer(F)
opt= 'y'
while opt=='y' or opt=='Y' :
No=int(input("Enter Employee Number: "))
Name=input("Enter Employee Name: ")
Sal=float(input ("Enter Employee Salary: "))
L=[No,Name,Sal]
W.writerow(L)
opt=input("Do you want to continue (y/n) ?")
F.close()
def Search():
F=open("Emp.csv",'r',newline='\r\n')
no=int(input("Enter Employee number to search : "))
found=0
row=csv.reader(F)
for data in row:
if data[0] == str(no) :
print("\nEmployee Deatils are:")
print(" ----------------------")
print("Name : ",data[1])
print("Salary: ",data[2])
print("-----------------------")
found=1
break
if found == 0:
print ("The searched Employee number is not Found")
F. close ()
#Main Program
Create ()
Search ()
Output:
#Practical No. 15 – Write a Program in Python Language to create a CSV file by entering userid and password,
read and search the password for given userid.
Source Code:
#Program No. - Write a Program in Python Language to Create a CSV file by
# entering userid and password, read and search the password for given userid.
import csv
def Create():
F=open ("userid.csv",'a', newline='')
W=csv.writer(F)
opt= 'y'
while opt=='y' or opt=='Y' :
uid=input("Enter User ID: ")
pwd=input("Enter Password: ")
L=[uid,pwd]
W.writerow(L)
opt=input("Do you want to continue (y/n) ?")
F.close()
def Search():
F=open("userid.csv",'r',newline='\r\n')
user=input("Enter the User ID to search : ")
found=0
row=csv.reader(F)
for data in row:
if data[0] == user :
print("\nUser ID Details are:")
print(" ----------------------")
print("User ID : ",data[0])
print("Password: ",data[1])
print("-----------------------")
found=1
break
if found == 0:
print ("The searched User ID is not Found")
F. close ()
#Main Program
Create ()
Search ()
Output :
# Practical No.16- Write a program using data file concepts to create a CSV file
# to store Employee Number, Employee Name and Employee Salary.
# Accept Employee Number of an employee and display Name and Salary
# of all Employees whose salary is more than 50000.
import csv
found=False
for row in myreader:
if len(row)!=0:
if float(row[2])>50000:
print("====================")
print("NAME : ",row[1])
print("SALARY : ",row[2])
found=True
break
if not found:
print("====================")
print(" EMPNO NOT FOUND")
print("====================")
ans=input("Search More?(Y)")
# PRACTICAL NO. 17 - Write a menu driven program to implement a STACK using a list.
# Menu to appear is "STACK OPERATIONS: 1. PUSH 2. POP 3. PEEK 4. DISPLAY STACK 5. EXIT"
# and related operations are to be performed as per the given choice.
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 peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]
def disp(stk):
if isempty(stk):
print("stack empty")
else:
top=len(stk)-1
print(stk[top],"<-top")
for a in range(top-1,-1,-1):
print(stk[a])
stack=[]
top=None
while True:
print("STACK OPERATIONS:")
print("1. PUSH")
print("2. POP")
print("3. PEEK")
print("4. DISPLAY STACK")
print("5. EXIT")
ch=int(input("Enter your choice:"))
if ch==1:
item=int(input("Enter item:"))
push(stack,item)
elif ch==2:
item=pop(stack)
if item=="underflow":
print("Stack is empty")
else:
print("Popped item is:",item)
elif ch==3:
item=peek(stack)
if item=="underflow":
print("Stack is empty")
else:
print("Topmost item is:",item)
elif ch==4:
disp(stack)
elif ch==5:
break
else:
print("Invalid Choice")
# Practical No. 18 - Write a Program to create a list containing integer values.
# With separate user defined functions perform the
# following operations based on this list.
# ● Traverse the content of the list and push the even numbers into a stack.
# ● Pop and display the content of the stack.
# For Example:
# If the sample Content of the list is as follows:
# N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
# Sample Output of the code should be:
# 38 22 98 56 34 12
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
for k in N:
if k%2==0:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
# Practical No. 19 - Write a Program to create a list containing integer values.
# With separate user defined functions perform the
# following operations based on this list.
# ● Traverse the content of the list and push the ODD numbers into a stack.
# ● Pop and display the content of the stack.
# For Example:
# If the sample Content of the list is as follows:
# N=[9,6,5,7,4]
# Sample Output of the code should be:
# Enter the values of List[9,6,5,7,4]
#759
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
for k in N:
if k%2==1:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
# Practical No.20 -Accept values of a dictionary containing names and marks as
#key value pairs. Write a program, with separate user
#defined functions to perform the following operations:
#● Push the keys (name of the student) of the dictionary into a
#stack, where the corresponding value (marks) is greater than 75.
#● Pop and display the content of the stack.
#For example:
#If the sample content of the dictionary is as follows:
#R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90,"TOM":82}
#The output from the program should be:
#TOM ANU BOB OM
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[]
for k in R:
if R[k]>=75:
PUSH(ST,k)
print(ST)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
PRACTICAL NO. 21 – SQL COMMANDS 1.
2. Create a student table with the student id, class, section, gender, name, dob, and marks as attributes where
the student id is the primary key.
mysql> use practical;
mysql> create table student(studentid int NOT NULL primary key, class int, section varchar(1), gender
varchar(1), name varchar(30), dob date, marks int);
5. Increase marks by 5% for those students who have studentid is more than 20.
mysql>update student set marks=marks+0.05*marks where studentid >20;
7. Display studentid, Name and Marks of those students who are scoring marks more than 50.
mysql>select studentid,name,marks from student where marks>50;
10. Add a new column email in the above table with appropriate data type.
mysql>alter table student add column email varchar(25);
11. Add the email ids of each student in the previously created email column.
mysql>update student set email=”aman123@gmail.com” where studentid=1;
mysql>update student set email=”priya456@gmail.com” where studentid=2;
mysql>update student set email=”aman123@gmail.com” where studentid=3;
mysql>update student set email=”priya456@gmail.com” where studentid=4;
mysql>update student set email=”aman123@gmail.com” where studentid=5;
mysql>update student set email=”priya456@gmail.com” where studentid=6;
mysql>update student set email=”aman123@gmail.com” where studentid=7;
mysql>update student set email=”priya456@gmail.com” where studentid=8;
mysql>update student set email=”aman123@gmail.com” where studentid=9;
mysql>update student set email=”priya456@gmail.com” where studentid=10;
12. Display the information of all the students, whose name starts with ‘AN’ (Examples: ANAND, ANGAD,..)
mysql>select * from student where name like “AN%”;
13. Display studentid, Name, DOB of those students who are born between ‘2005- 01-01’ and ‘2005-12-31’.
mysql>select studentid,name,dob from student where dob between ‘2005- 01-01’ and ‘2005-12-31’;
14. Display studentid, Name, DOB, Marks, Email of those male students in ascending order of their names.
mysql>select studentid,name,dob,marks,email from student where gender=”M” order by name
ascending;
15. Display studentid, Gender, Name, DOB, Marks, Email in descending order of their marks.
mysql>select studentid,gender,name,dob,marks,email from student order by marks descending;
Solution:-
mysql> INSERT INTO EMP VALUES(8369,'SMITH','CLERK','1990-12-18',800,NULL);
Query OK, 1 row affected (0.06 sec)
mysql> INSERT INTO EMP VALUES(8499,'ANYA','SALESMAN','1991-02-20',1600.00,300.00);
Query OK, 1 row affected (0.06 sec)
mysql> INSERT INTO EMP VALUES(8521,'SETH','SALESMAN','1991-02-22',1250.00,500.00);
Query OK, 1 row affected (0.07 sec)
mysql> INSERT INTO EMP VALUES(8566,'MAHADEVAN','MANAGER','1991-04-02',2985.00,NULL);
Query OK, 1 row affected (0.05 sec)
mysql> INSERT INTO EMP VALUES(8654,'MOMIN','SALESMAN','1991-09-28',1250.00,400.00);
Query OK, 1 row affected (0.06 sec)
mysql> INSERT INTO EMP VALUES(8698,'BINA','MANAGER','1991-05-01',2850.00,NULL);
Query OK, 1 row affected (0.07 sec)
mysql> INSERT INTO EMP VALUES(8882,'SHIVANSH','MANAGER','1991-06-09',2450.00,NULL);
Query OK, 1 row affected (0.02 sec)
mysql> INSERT INTO EMP VALUES(8888,'SCOTT','ANALYST','1992-12-09',3000.00,NULL);
Query OK, 1 row affected (0.06 sec)
mysql> INSERT INTO EMP VALUES(8839,'AMIR','PRESIDENT','1991-11-18',5000.00,NULL);
Query OK, 1 row affected (0.06 sec)
mysql> INSERT INTO EMP VALUES(8844,'KULDEEP','SALESMAN','1991-09-08',1500.00,0.00);
Query OK, 1 row affected (0.06 sec)
Q4. Write a query to display all the records with all the columns.
Solution:-
mysql> SELECT * FROM EMP;
+-------+-----------+-------------+------------+------+------+
| EmpID | EmpName | Designation | DOJ | Sal | Comm |
+-------+-----------+-------------+------------+------+------+
| 8369 | SMITH | CLERK | 1990-12-18 | 800 | NULL |
| 8499 | ANYA | SALESMAN | 1991-02-20 | 1600 | 300 |
| 8521 | SETH | SALESMAN | 1991-02-22 | 1250 | 500 |
| 8566 | MAHADEVAN | MANAGER | 1991-04-02 | 2985 | NULL |
| 8654 | MOMIN | SALESMAN | 1991-09-28 | 1250 | 400 |
| 8698 | BINA | MANAGER | 1991-05-01 | 2850 | NULL |
| 8882 | SHIVANSH | MANAGER | 1991-06-09 | 2450 | NULL |
| 8888 | SCOTT | ANALYST | 1992-12-09 | 3000 | NULL |
| 8839 | AMIR | PRESIDENT | 1991-11-18 | 5000 | NULL |
| 8844 | KULDEEP | SALESMAN | 1991-09-08 | 1500 | 0 |
+-------+-----------+-------------+------------+------+------+
10 rows in set (0.00 sec)
Q5. Write a query to display EmpName and Sal of employees whose salary are greater than or equal to 2200
Solution:-
mysql> SELECT EmpName,Sal FROM EMP WHERE Sal>=2200;
+-----------+------+
| EmpName | Sal |
+-----------+------+
| MAHADEVAN | 2985 |
| BINA | 2850 |
| SHIVANSH | 2450 |
| SCOTT | 3000 |
| AMIR | 5000 |
+-----------+------+
5 rows in set (0.00 sec)
Q6. Write a query to display employee name and salary of those employees who don’t have their salary in range
of 2500 to 4000.
Solution:-
mysql> SELECT EmpName,Sal FROM EMP WHERE Sal NOT BETWEEN 2500 AND 4000;
+----------+------+
| EmpName | Sal |
+----------+------+
| SMITH | 800 |
| ANYA | 1600 |
| SETH | 1250 |
| MOMIN | 1250 |
| SHIVANSH | 2450 |
| AMIR | 5000 |
| KULDEEP | 1500 |
+----------+------+
7 rows in set (0.00 sec)
Q7. Write a query to display the name of employee whose name contains “A” as third alphabet in Ascending
order of employee names.
Solution:-
mysql> SELECT EmpName FROM EMP WHERE EmpName LIKE '_ _A%' ORDER BY EmpName;
Empty set (0.00 sec)
Q8. Write a query to display the ename and sal with 50% of sal as DA.
Solution:-
mysql> SELECT EmpName,Sal,Sal*0.50 AS DA FROM EMP;
+-----------+------+---------+
| EmpName | Sal | DA |
+-----------+------+---------+
| SMITH | 800 | 400.00 |
| ANYA | 1600 | 800.00 |
| SETH | 1250 | 625.00 |
| MAHADEVAN | 2985 | 1492.50 |
| MOMIN | 1250 | 625.00 |
| BINA | 2850 | 1425.00 |
| SHIVANSH | 2450 | 1225.00 |
| SCOTT | 3000 | 1500.00 |
| AMIR | 5000 | 2500.00 |
| KULDEEP | 1500 | 750.00 |
+-----------+------+---------+
10 rows in set (0.00 sec)
Q9. Write a query to display details of employees with the text “Not given”, if commission is null.
Solution:-
mysql> SELECT EmpID,EmpName,Designation,DOJ,Sal,'Not Given' AS 'Comm' FROM EMP WHERE Comm IS NULL;
+-------+-----------+-------------+------------+------+-----------+
| EmpID | EmpName | Designation | DOJ | Sal | Comm |
+-------+-----------+-------------+------------+------+-----------+
| 8369 | SMITH | CLERK | 1990-12-18 | 800 | Not Given |
| 8566 | MAHADEVAN | MANAGER | 1991-04-02 | 2985 | Not Given |
| 8698 | BINA | MANAGER | 1991-05-01 | 2850 | Not Given |
| 8882 | SHIVANSH | MANAGER | 1991-06-09 | 2450 | Not Given |
| 8888 | SCOTT | ANALYST | 1992-12-09 | 3000 | Not Given |
| 8839 | AMIR | PRESIDENT | 1991-11-18 | 5000 | Not Given |
+-------+-----------+-------------+------------+------+-----------+
6 rows in set (0.02 sec)
Q4. Add Foreign Key as DeptID which refers DeptID column of DEPT table.
Solution:-
mysql> ALTER TABLE EMP ADD FOREIGN KEY (DeptID)REFERENCES DEPT(DeptID);
Query OK, 10 rows affected (0.22 sec)
Records: 10 Duplicates: 0 Warnings: 0
Q5. Update DeptID of EMP Table with valid DeptIDs to link both tables.
Solution:-
mysql> UPDATE EMP,DEPT SET EMP.DEPTID=DEPT.DEPTID WHERE EMP.EMPID= DEPT.MGRID;
Query OK, 4 rows affected (0.06 sec)
Rows matched: 4 Changed: 4 Warnings: 0
+----------+
| COUNT(*) |
+----------+
| 1|
+----------+
1 row in set (0.00 sec)
Q8. Display the Designation wise list of employees with name, Sal and Date of Joining.
Solution:-
mysql> SELECT EmpName,Designation,Sal,DOJ as 'DateOfJoining'FROM EMP ORDER BY Designation;
+-----------+-------------+------+---------------+
| EmpName | Designation | Sal | DateOfJoining |
+-----------+-------------+------+---------------+
| SCOTT | ANALYST | 3000 | 1992-12-09 |
| SMITH | CLERK | 800 | 1990-12-18 |
| MAHADEVAN | MANAGER | 2985 | 1991-04-02 |
| SHIVANSH | MANAGER | 2450 | 1991-06-09 |
| BINA | MANAGER | 2850 | 1991-05-01 |
| AMIR | PRESIDENT | 5000 | 1991-11-18 |
| SETH | SALESMAN | 1250 | 1991-02-22 |
| MOMIN | SALESMAN | 1250 | 1991-09-28 |
| ANYA | SALESMAN | 1600 | 1991-02-20 |
| KULDEEP | SALESMAN | 1500 | 1991-09-08 |
+-----------+-------------+------+---------------+
10 rows in set (0.00 sec)
Q9. Count the number of employees who are not getting commission.
Solution:-
mysql> SELECT COUNT(*) FROM EMP WHERE COMM IS NULL;
+----------+
| COUNT(*) |
+----------+
| 6|
+----------+
1 row in set (0.00 sec)
+----------+
| empname |
+----------+
| BINA |
| SHIVANSH |
+----------+
Q13. Display the name of employees who are working in Delhi and getting more than 2000.
Solution:-
mysql> select empname from emp,dept where location='delhi'and sal>2000 and emp.empid=dept.mgrid;
+----------+
| empname |
+----------+
| BINA |
| SHIVANSH |
+----------+
2 rows in set (0.00 sec)
Q14. Write a query to display details of employs who are not getting commission.
Solution:-
mysql> SELECT * FROM EMP WHERE COMM IS NULL;
+-------+-----------+-------------+------------+------+------+
| EmpID | EmpName | Designation | DOJ | Sal | Comm |
+-------+-----------+-------------+------------+------+------+
| 8369 | SMITH | CLERK | 1990-12-18 | 800 | NULL |
| 8566 | MAHADEVAN | MANAGER | 1991-04-02 | 2985 | NULL |
| 8698 | BINA | MANAGER | 1991-05-01 | 2850 | NULL |
| 8882 | SHIVANSH | MANAGER | 1991-06-09 | 2450 | NULL |
| 8888 | SCOTT | ANALYST | 1992-12-09 | 3000 | NULL |
| 8839 | AMIR | PRESIDENT | 1991-11-18 | 5000 | NULL |
+-------+-----------+-------------+------------+------+------+
6 rows in set (0.00 sec)
PRACTICAL NO. 24-– SQL COMMANDS 4.
Write queries (1) to (10) based on the tables EMPLOYEE and DEPARTMENT given below:
mysql> create table EMPLOYEE(EMPID INTEGER, NAME VARCHAR(25), DOB DATE, DEPTID VARCHAR(20), DESIG
VARCHAR(25), SALARY INTEGER);
Query OK, 0 rows affected (0.12 sec)
mysql> insert into EMPLOYEE values(123, "Nitin", "1977-10-10", "D002", "AO", 59000);
Query OK, 1 row affected (0.03 sec)
mysql> insert into EMPLOYEE values(129, "Navjot", "1971-07-12", "D003", "Supervisor", 40000);
Query OK, 1 row affected (0.03 sec)
mysql> insert into EMPLOYEE values(130, "Jimmy", "1980-12-30", "D004", "Sales Rep", Null);
Query OK, 1 row affected (0.03 sec)
mysql> insert into EMPLOYEE values(131, "Faiz", "1984-4-06", "D001", "Dep Manager", 65000);
Query OK, 1 row affected (0.03 sec)
Q8. To display name and respective department name of each employee whose salary is more than 50000.
mysql> SELECT NAME, DEPTNAME FROM EMPLOYEE, DEPARTMENT WHERE
EMPLOYEE.DEPTID=DEPARTMENT.DEPTID AND SALARY>50000;
+--------+----------+
| NAME | DEPTNAME |
+--------+----------+
| Alisha | Personal |
| Nitin | Admin |
| Faiz | Personal |
+--------+----------+
3 rows in set (0.00 sec)
Q9. To display the names of employees whose salary is not known, in alphabetical order.
mysql> SELECT NAME FROM EMPLOYEE WHERE SALARY IS NULL ORDER BY NAME;
+-------+
| NAME |
+-------+
| Jimmy |
+-------+
1 row in set (0.00 sec)
2. Create a table shop with fields - pid integer, pname varchar(20), price double, SID Integer.
mysql> use purchase;
mysql> create table shop(pid integer, pname varchar(20), price double, SID Integer);
Query OK, 0 rows affected (2.03 sec)
5. Create a table store with fields - SID Integer, sname varchar(20), loc varchar(20)
mysql> create table store(SID Integer, sname varchar(20), loc varchar(20));
Query OK, 0 rows affected (2.25 sec)
7. Write query to display SID, sum of price group wise as per SID from table shop .
mysql> select SID,sum(price) from shop GROUP BY SID;
+------+------------+
| SID | sum(price) |
+------+------------+
| 111 | 14 |
| 222 | 56 |
| 333 | 35 |
+------+------------+
3 rows in set (0.02 sec)
8. Write query to display SID, count of each SID from table shop .
mysql> select sid, count(*) from shop group by SID;
+------+----------+
| sid | count(*) |
+------+----------+
| 111 | 1|
| 222 | 2|
| 333 | 2|
+------+----------+
3 rows in set (0.06 sec)
9. Write query to display SID, Sum of price of SID=222 from table shop.
mysql> select SID, sum(price) from shop GROUP BY SID having SID=222;
+------+------------+
| SID | sum(price) |
+------+------------+
| 222 | 56 |
+------+------------+
1 row in set (0.64 sec)
10. Write query to display PID,PNAME,PRICE from table shop and SNAME,LOC from table store.
mysql> select pid,pname,price,sname,loc from shop,store where shop.sid=store.sid;
+-----+----------+-------+----------------+-----------+
| pid | pname | price | sname | loc |
+-----+----------+-------+----------------+-----------+
| 1 | Lux | 18 | Arpan Stores | Patna |
| 2 | Dettol | 16 | Ayangar Stores | Chennai |
| 3 | Lifebuoy | 14 | Deppak Stores | New Delhi |
| 4 | Ponds | 19 | Ayangar Stores | Chennai |
| 5 | Dove | 38 | Arpan Stores | Patna |
+-----+----------+-------+----------------+-----------+
5 rows in set (0.45 sec)
11. Write query to display PID,PNAME,PRICE,SID from table shop and SNAME,LOC from table store.
mysql> select pid,pname,price,shop.sid,sname,loc from shop,store where shop.sid=store.sid;
+-----+----------+-------+------+----------------+-----------+
| pid | pname | price | sid | sname | loc |
+-----+----------+-------+------+----------------+-----------+
| 1 | Lux | 18 | 222 | Arpan Stores | Patna |
| 2 | Dettol | 16 | 333 | Ayangar Stores | Chennai |
| 3 | Lifebuoy | 14 | 111 | Deppak Stores | New Delhi |
| 4 | Ponds | 19 | 333 | Ayangar Stores | Chennai |
| 5 | Dove | 38 | 222 | Arpan Stores | Patna |
+-----+----------+-------+------+----------------+-----------+
5 rows in set (0.00 sec)
12. Write query to display PID,PNAME,PRICE,SID from table shop and SNAME,LOC from table store for Product
Name “Ponds”.
mysql> select pid,pname,price,shop.sid,sname,loc from shop,store where pname="Ponds" AND
shop.sid=store.sid;
+-----+-------+-------+------+----------------+---------+
| pid | pname | price | sid | sname | loc |
+-----+-------+-------+------+----------------+---------+
| 4 | Ponds | 19 | 333 | Ayangar Stores | Chennai |
+-----+-------+-------+------+----------------+---------+
1 row in set (0.41 sec)
13. Write query to display PID,PNAME,PRICE,SID from table shop and SNAME,LOC from table store in
ascending order of price;
mysql> select pid,pname,price,A.sid,sname,loc from shop A,store B where A.sid=B.sid order by price;
+-----+----------+-------+------+----------------+-----------+
| pid | pname | price | sid | sname | loc |
+-----+----------+-------+------+----------------+-----------+
| 3 | Lifebuoy | 14 | 111 | Deppak Stores | New Delhi |
| 2 | Dettol | 16 | 333 | Ayangar Stores | Chennai |
| 1 | Lux | 18 | 222 | Arpan Stores | Patna |
| 4 | Ponds | 19 | 333 | Ayangar Stores | Chennai |
| 5 | Dove | 38 | 222 | Arpan Stores | Patna |
+-----+----------+-------+------+----------------+-----------+
5 rows in set (0.02 sec)
14. Write query to display all record of table shop whose SID is same as that of pname as “LUX”.
mysql> select * from shop where sid= (select sid from shop where pname="LUX");
+-----+-------+-------+------+
| pid | pname | price | SID |
+-----+-------+-------+------+
| 1 | Lux | 18 | 222 |
| 5 | Dove | 38 | 222 |
+-----+-------+-------+------+
2 rows in set (0.08 sec)
15. Write query to display record having maximum price from table shop.
mysql> select * from shop where price=(select max(price) from shop);
+-----+-------+-------+------+
| pid | pname | price | SID |
+-----+-------+-------+------+
| 5 | Dove | 38 | 222 |
+-----+-------+-------+------+
1 row in set (0.03 sec)
# Practical No. 26 - Write a program using MYSQL-PYTHON database connectivity to create
# a database school, then create a table student (Roll INT(4)
# primary key,Name VARCHAR(20),AGE INT(2), CITY CHAR(10),
# MARKS INT(3) in this database which should then store any
# two records in it and then display only those records
# city is "LUCKNOW"
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root")
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE school")
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="school")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE student (Roll INT(4) primary key,Name VARCHAR(20),AGE INT(2), CITY
CHAR(10), MARKS INT(3))")
sql="INSERT INTO STUDENT (ROLL,NAME,AGE,CITY,MARKS) VALUES (%s,%s,%s,%s,%s)"
val=(101,'Pankaj',15,'Barabanki',300)
mycursor.execute(sql,val)
sql="INSERT INTO STUDENT (ROLL,NAME,AGE,CITY,MARKS) VALUES (%s,%s,%s,%s,%s)"
val=(102,'anuj',16,'Lucknow',290)
mycursor.execute(sql,val)
mycursor.execute("select * from student where city='LUCKNOW'")
myresult=mycursor.fetchall()
for x in myresult:
print(x)
Output:
#Practical No. 27 - Write a program using MYSQL-PYTHON database connectivity to create a
database school, then create a table student in this database which should
# then store any two records in it and then display only those records where AGE<=15
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root")
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE School")
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="school")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE student (Roll INT(4) primary key,Name VARCHAR(20),AGE
INT(2), CITY CHAR(10), MARKS INT(3))")
sql="INSERT INTO STUDENT (ROLL,NAME,AGE,CITY,MARKS) VALUES (%s,%s,%s,%s,%s)"
val=(101,'Pankaj',15,'Barabanki',300)
mycursor.execute(sql,val)
sql="INSERT INTO STUDENT (ROLL,NAME,AGE,CITY,MARKS) VALUES (%s,%s,%s,%s,%s)"
val=(102,'anuj',16,'Lucknow',290)
mycursor.execute(sql,val)
mycursor.execute("select * from student where AGE<=15")
myresult=mycursor.fetchall()
for x in myresult:
print(x)
# Practical No. 28 - Write a program using MYSQL-PYTHON database connectivity to
# create a database school, then create a table student in this database which
# should then store any two records in it and then display only those records
# where marks>=300
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root")
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE School")
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="school")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE student (Roll INT(4) primary key,Name VARCHAR(20),AGE
INT(2), CITY CHAR(10), MARKS INT(3))")
sql="INSERT INTO STUDENT (ROLL,NAME,AGE,CITY,MARKS) VALUES (%s,%s,%s,%s,%s)"
val=(101,'Pankaj',15,'Barabanki',300)
mycursor.execute(sql,val)
sql="INSERT INTO STUDENT (ROLL,NAME,AGE,CITY,MARKS) VALUES (%s,%s,%s,%s,%s)"
val=(102,'anuj',16,'Lucknow',290)
mycursor.execute(sql,val)
mycursor.execute("select * from student where marks>=300")
myresult=mycursor.fetchall()
for x in myresult:
print(x)
# Practical No. 29 - To write a Program using PYTHON-MYSQL Connectivity to insert records in Emp
# table and display the records. Use While loop to store multiple records.
import mysql.connector
con=mysql.connector.connect(host='localhost',username='root',password='root',database='emplo
yees')
if con.is_connected():
cur=con.cursor()
opt='y'
while opt == 'y' or opt=='Y':
No=int(input("Enter Employee Number: "))
Name=input("Enter Employee Name: ")
Gender=input("Enter Employee Gender (M/F) : ")
Salary=int(input("Enter Employee Salary: "))
Query="INSERT INTO EMP VALUES ( { } , ' {}', '{}', {}) ". format (No, Name, Gender, Salary)
cur.execute (Query)
con. commit ()
print ("Record Stored Successfully")
opt=input ("Do you want to add another employee details (y/n) :")
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root")
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE School5")
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="school5")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE student (Roll INT(4) primary key,Name VARCHAR(20),AGE
INT(2), CITY CHAR(10), MARKS INT(3))")
n=int(input("Enter number of records to be entered ? "))
for k in range(1,n+1,1):
print("\nEnter record ",k)
ROLL=int(input("Enter Roll Number ? "))
NAME=input("Enter Name ? ")
AGE=int(input("Enter Age ? "))
CITY=input("Enter City ? ")
MARKS=int(input("Enter Marks ? "))
sql="INSERT INTO STUDENT VALUES ({},'{}',{},'{}',{})".format(ROLL,NAME,AGE,CITY,MARKS)
mycursor.execute(sql)
mydb.commit()
print("\nRecords containing city as LUCKNOW are :")
mycursor.execute("select * from student where city='LUCKNOW'")
myresult=mycursor.fetchall()
for x in myresult:
print(x)
mydb.close()
BIBLIOGRAPHY