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

Cs Practical

The document describes a Python program to create a binary file to store student roll numbers and names. It allows writing data to the file, displaying all records, and searching for a roll number to display the corresponding name. Functions are defined to write, read and search the binary file. The main program runs a menu loop for the user to choose these options or exit.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Cs Practical

The document describes a Python program to create a binary file to store student roll numbers and names. It allows writing data to the file, displaying all records, and searching for a roll number to display the corresponding name. Functions are defined to write, read and search the binary file. The main program runs a menu loop for the user to choose these options or exit.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

CERTIFICATE

This is to certify that PRASHANT of class 12th “ B ”

of GREEN VIEW PUBLIC SCHOOL has successfully

completed his/her Practical File in Computer Science as

prescribed by CBSE in the year 2023-2024.

Roll no.:-29

Principal Ms. Urvashi Sondhi


Green View Public School (PGT CS)
Acknowledgement
It is with great pleasure that I find myself penning down these lines to express my sincere

thanks to various people who helped me a long way to complete this Practical File.

The harmonies climate in our school provided proper guidance for preparing this file.

It was my privilege to have been guided by Ms.Urvashi Sondhi.

Thanks to all my classmates who helped during the development of this file with their

constructive advice.

Name:PRASHANT GUPTA
Class:-12 B
Roll no.:-29
AISSCE PRACTICAL EXAM 2023 COMPUTER
SCIENCE PRACTICAL LIST AS PER CBSE
CURRICULUM PYTHON PROGRAMS
1. Write a program using function to find the factorial of a natural number.
2. Write a program to Input any number from user and check it is Prime no. or not
3. Write a program using function to compute the nth Fibonacci number.
4. Write a program using function to find the sum of all elements of a list.
5. Program to search any word in given string/sentence
6. Read a text file line by line and display each word separated by a #.
7. Read a text file and display the number of vowels/ consonants/ uppercase/
lowercase characters in the file.
8. Create a binary file with name and roll number. Search for a given roll
number and display the name, if not found display appropriate message.
9. Create a binary file with roll number, name and marks. Input a roll number and
update the marks.
10. Remove all the lines that contain the character `a' in a file and write it to
another file.
11. Write a random number generator that generates random numbers between 1 and
6 (simulates a dice).
12. Write a Python program to implement a stack using a list data-structure.
13. Write a Python program to implement a queue using a list data-structure.
14. Take a sample of ten phishing e-mails (or any text file) and find most commonly
occurring word(s).
15. Create a CSV file with EmpNo, Emp name and Salary.Search for a given EmpNo
and display the name and salary,if not found display appropriate message.
16. Write a python program to implement python Mathematical functions.
17. Write a python program to implement python String functions.
18. Write a python program to make user define module and import same in another
module or program.
19. Integrate SQL with Python by importing the MYSQL module to create a table Employee.
20. Integrate SQL with Python by importing the MYSQL module to Insert records in
Employee.
21. Integrate SQL with Python by importing the MYSQL module to search an employee
using Empno and if present in table display the record, if not display appropriate
message.
22. Integrate SQL with Python by importing the MYSQL module to search a Employee using
Empno, update the record.
23. Integrate SQL with Python by importing the MYSQL module to search a Employee using
Empno and if present in table delete the record.
Database Management
 Create a student table and insert data.
 Implement the following SQL commands on the student table:
 ALTER table to add new attributes/modify data type/drop attribute.
 UPDATE table to modify data.
 ORDER BY to display data in ascending / descending order.
 DELETE to remove tuple(s).
 GROUP BY and find the min, max, sum, count and average.

Program 1: Write a program using function to find the factorial of a natural number.
def factorial(a):
fact = 1
n = num # storing num in n for printing
while num>1:
fact = fact * num
num-=1
return fact

n=int(input("Enter a Number:"))
res=factorial(n)
print("Factorial of ",n,"is",res)

OUTPUT
Enter any number : 8
Factorial of 8 is :
40,320
Program 2: Input any number from user and check it is Prime no. or not

import math
num = int(input("Enter any number :"))
isPrime = True
for i in range(2,int(math.sqrt(num))
+1): if num % i == 0:
isPrime=False

if isPrime:
print("## Number is Prime ##")
else:
print("## Number is not Prime ##")

OUTPUT
Enter any number :112
## Number is not Prime ##
>>>
Enter any number :118
## Number is not Prime ##
>>>
Enter any number :113
## Number is Prime ##
>>>
Enter any number :5
## Number is Prime
##
>>>
Enter any number :17
## Number is Prime ##
Program 3: Write a program using function to compute the nth Fibonacci number.

def
fibo(n)
: a=1
b=
1
c=
0
i=
3

if n==1:
print(a
) else:
while i<=n:
c=a+
b
a=b
b=c
i=i+
1
print("nth term of Fibonacci series of ",n,"is",c)

n=int(input("Enter a
Number:")) fibo(n)

OUTPUT
Enter the 'n' term to find in fibonacci :10
10 th term of fibonacci series is : 55
Program 4:Write a program using function to find the sum of all elements of a list.

def sumelements(n):
lst=[ ]

for n in range(num):
numbers=int(input("Enter a number:"))
lst.append(numbers)

sumlist=sum(lst)
return sumlist

num=int(input("How many numbers to sum in a


list:")) sumlist=sumelements(num)
print("Sum of Elements in a

list:",sumlist) OUTPUT:

How many numbers to sum in a


list:4
Enter a number:12
Enter a
number:22 Enter
a number:32
Enter a
number:42
Sum of Elements in a list: 108
Program 5: Program to search any word in given string/sentence.

#Program to find the occurence of any word in a string


def countWord(str1,word):
s = str1.split()
count=0
for w in s:
if w==word:
count+=1
return count

str1 = input("Enter any sentence :")


word = input("Enter word to search in sentence :")
count = countWord(str1,word)
if count==0:
print("## Sorry! ",word," not present ")
else:
print("## ",word," occurs ",count," times ## ")

OUTPUT

Enter any sentence : orange is orange


Enter word to search in sentence :orange
## orange occurs 2 times ##

Enter any sentence :learning cs is fun


Enter word to search in sentence :java
## Sorry! java not present
Program 6: Read a text file line by line and display each word separated by a #.

f=open("Story.txt","a")
s=input("Enter a Story")
f.write(s)
f.close()
f=open("Story.txt","r")
l=f.readline().split()
for w in l:
print(w,end='#')

Output:
Enter a Story: Once upon a time there was magician, who is very Intelligent and
magical too.
Once#upon#a#time#there#was#magician,#who#is#very#Intelligent#and#magical#too.#
Program 7: Program to read the content of file and display the total
number of consonants, uppercase, vowels and lower case characters‟

#Program to read content of file


#and display total number of vowels, consonants, lowercase and uppercase characters

f =
open("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()

NOTE : if the original content of file is:


India is my country
I love python
Python learning is fun
123@

OUTPUT
Total Vowels in file : 16
Total Consonants in file n : 30
Total Capital letters in file : 2
Total Small letters in file : 44
Total Other than letters : 4
Program 8: Program to create binary file to store Rollno and Name, Search
any Rollno and display name if Rollno found otherwise “Rollno not
found”

import
pickle
import sys

dict={ }

def write_in_file():
file=open("Student.dat","ab") # a-append, b-
binary no=int(input("Enter no of Students"))
for i in range(no):
print("Enter Student ",i+1,"details")
dict["roll"]=int(input("Enter the Roll no:"))
dict["name"]=input("Enter the Name:")
pickle.dump(dict,file) # dump-to write in student file
file.close()

def display():
# read from file and display
file=open("Student.dat","rb") # r-read , b-binary
try:
while True:
stud=pickle.load(file) # reads from file
print(stud)
except EOFError:
pass
file.close()

def search():
file=open("student.dat","rb") # r-read , b-
binary r=int(input("Enter the rollno to
search")) found=0
try:
while True:
data=pickle.load(file) # reads from file
if data["roll"]==r:
print("Record found")
print(data)
found=
1
break
except EOFError:
pass
if found==0:
print("Record not found")
file.close()
# main
program while
True:
print("Menu \n 1-Write in a file \n 2- Display \n 3-Search \n 4-Exit \
n") ch=int(input("Enter your choice"))
if ch==1:
write_in_file(
) if ch==2:
display(
) if ch==3:
search(
) if ch==4:
print("Thank you")
sys.exit()

OUTPUT:

Menu
1-Write in a
file 2- Display
3-
Search
4-Exit

Enter your choice:1

Enter no of Students:3
Enter Student 1 details
Enter the Roll no:1
Enter the Name:sahil
kumar
Enter Student 2 details
Enter the Roll no:2
Enter the Name:sita
Enter Student 2
details
Enter the Roll no:3
Enter the name:ajay
Menu
1-Write in a
file 2- Display
3-
Search
4-Exit

Enter your choice:2


{'roll': 1, 'name': 'sahil kumar'}
{'roll': 2, 'name': 'sita '}

{‘roll’: 3,’name’:’ajay’}

Menu

1-Write in a
file 2- Display
3-
Search
4-Exit
Enter your choice:3

Enter the rollno to search:2

Record found
{'roll': 2, 'name': 'sita '}

Menu
1-Write in a
file 2- Display
3-
Search
4-Exit

Enter your choice:4


Thank you
Program 9 : Create a binary file with roll number, name and marks. Input a roll number
and update the marks.

import pickle # for pickle.dump(),


pickle.load() import sys # for sys.exit()
function
import os # for os.remove(),
os.rename() dict={ }

def write_in_file():
file=open("Student.dat","ab") # a-append, b-binary
no=int(input("Enter no of Students"))
for i in range(no):
print("Enter Student ",i+1,"details")
dict["roll"]=int(input("Enter the Roll no:"))
dict["name"]=input("Enter the Name:")
dict["Marks"]=input("Enter the Marks:")
pickle.dump(dict,file) # dump-to write in student file
file.close()

def display():
# read from file and display
file=open("Student.dat","rb") # r-read , b-binary
try:
while True:
stud=pickle.load(file) # reads from file
print(stud)
except EOFError:
pass
file.close()

def search():
file=open("student.dat","rb") # r-read , b-
binary r=int(input("Enter the rollno to
search")) found=0
try:
while True:
data=pickle.load(file) # reads from file
if data["roll"]==r:
print("Record found")
print(data)
found=
1
break
except EOFError:
pass
if found==0:
print("Record not found")
file.close()
def update():
file1=open("student.dat","rb") # r-read, b-binary
file2=open("temp.dat","ab") # a-append b-
binary r=int(input("Enter the rollno to update"))
try:
while True:
data=pickle.load(file1) # reads from file
if data["roll"]==r:
print("Enter the new marks for the student:")
data["Marks"]=int(input("Enter the Marks:"))
pickle.dump(data,file2)
else:
pickle.dump(data,file2)
except EOFError:
pass
file1.close(
)
file2.close(
)
os.remove("student.dat")
os.rename("temp.dat","student.dat")
file=open("student.dat","rb") #r-read,b-binary
try:
while True:
stud=pickle.load(file)
print(stud)
except EOFError:
pass
file.close()

# main

program while

True:
print("Menu \n 1-Write in a file \n 2- Display \n 3-Search \n 4-Update \n 5-Exit \
n") ch=int(input("Enter your choice"))
if ch==1:
write_in_file()
if ch==2:
display(
) if ch==3:
search(
) if ch==4:
update(
) if ch==5:
print("Thank you")
sys.exit()
OUTPUT:
Menu
1-Write in a
file 2-Display
3-
Search
4-
Update
5-Exit
Enter your
choice2
Menu
1-Write in a
file 2-Display
3-
Search
4-
Update
5-Exit
Enter your choice1
Enter no of Students2
Enter Student 1
details Enter the Roll
no:1
Enter the Name:seema
Enter the Marks:20
Enter Student 2
details Enter the Roll
no:2
Enter the Name:Divya
Enter the Marks:20
Menu
1-Write in a
file 2-Display
3-
Search
4-
Update
5-Exit
Enter your choice2
{'roll': 1, 'name': 'seema', 'Marks': '20'}
{'roll': 2, 'name': 'Divya', 'Marks': '20'}
Menu
1-Write in a
file 2-Display
3-
Search
4-
Update
5-Exit
Enter your choice3
Enter the rollno to update2
Enter the new marks for the student:
Enter the Marks:15
{'roll': 1, 'name': 'seema', 'Marks': '20'}
{'roll': 2, 'name': 'Divya', 'Marks': 15}
Menu
1-Write in a
file 2- Display
3-
Search
4-
Update
5-Exit

Enter your choice5

Thank you
Q10.Remove all the lines that contain the character `a' in a file and write it to
another file.

f1 = open("first.txt","r" )
lines=f1.readlines()
f1.close()
f1=open("first.txt","w")
f2=open("second.txt","w")
for line in lines:
if 'a' in line:
f2.write(line
)
else:
f1.write(line)
print("All lines removed which contain 'a' from
first.txt") print("All lines added in Second.txt file
which contain a") f1.close()
f2.close(

) OUTPUT:

Content in first.txt after the execution of program

But never her loss of innocence.

Content in second.txt after the execution of program

A child’s trust in his father.


Guiding his to unfamiliar skin,
You never saw her as your son . Where
love and nurture should have been,
In their place was lust and forcefulness.
He was supposed to be a part of many firsts,
In his arms that I grew, Never realized that
Program 11.Write a random number generator that generates random numbers between 1 and 6
(simulates a dice).

import
random
import time
print("Press CTRL+C to stop the dice ")
play='y'
while play=='y':
try:
while True:
for i in range(10):
print()
n = random.randint(1,6)
print(n,end='')
time.sleep(.00001)
except KeyboardInterrupt:
print("Your Number is :",n)
ans=input("Play More? (Y) :")
if ans.lower()!='y':
play='n
' break

OUTPUT

Your Number is :
5
Play More? (Y) :y
Your Number is :
3 Play More? (Y)
:y Your Number is
: 2 Play More?
(Y) :n
Program 12: Program to implement Stack in Python using List

def isEmpty(S):
if len(S)==0:
return
True else:
return False

def
Push(S,item):
S.append(item)
top=len(S)-1

def Pop(S):
if isEmpty(S):
return "Underflow"
else:
val = S.pop()
if len(S)==0:
top=Non
e else:
top=len(S)-
1 return val

def Peek(S):
if isEmpty(S):
return "Underflow"
else:
top=len(S)-1
return S[top]

def Show(S):
if isEmpty(S):
print("Sorry No items in Stack ")
else:
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ')
t-=1
print()

# main begins
here S=[] #Stack
top=None
while True:
print("**** STACK DEMONSTRATION ******")
print("1. PUSH ")
print("2. POP")
print("3. PEEK")
print("4. SHOW STACK ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Push :"))
Push(S,val)
elif ch==2:
val = Pop(S)
if val=="Underflow":
print("Stack is Empty")
else:
print("\nDeleted Item was :",val)
elif ch==3:
val = Peek(S)
if val=="Underflow":
print("Stack Empty")
else:
print("Top Item :",val)
elif ch==4:
Show(S
) elif
ch==0:
print("Bye"
) break

OUTPUT
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :20
Cont…

0. EXIT
Enter your choice :1
Enter Item to Push :30

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :40

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :4
(Top) 40 <== 30 <== 20 <==

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :3
Top Item : 40

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :2

Deleted Item was : 40


**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :4
(Top) 30 <== 20 <==

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :0
Bye
Program 13: Program to take 10 sample phishing email, and find the most common word
occurring.

phishingemail=[
"[email protected]",
[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]"
]
myd={}
for e in phishingemail:
x=e.split('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max = max(myd,key=myd.get)
print("Most Common Occuring word is :",key_max)

OUTPUT

Most Common Occuring word is : lottery.com


14. Create a CSV file with EmpNo, Emp name and Salary.Search for a given EmpNo
and display the name and salary,if not found display appropriate message.

import csv

with open('myfile.csv',mode='a') as csvfile:


mywriter=csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee
Number:")) name=input("Enter Employee
Name:")
salary=int(input("Enter Employee Salary:"))
mywriter.writerow([eno,name,salary])
print("## Data Saved...##")
ans=input("Add More?")
ans='y'
with open('myfile.csv',mode='r') as csvfile:
myreader=csv.reader(csvfile,delimiter=',')
while ans=='y':
found=False
eno=int(input("Enter Employee Number to search:"))
for row in myreader:
if len(row)!=0:
if int(row[0])==eno:
print("===================")
print("Name :",row[1])
print("Salary :",row[2])
found=True
brea
k if not
found:
print("===================")
print(" EMPNO NOT
FOUND")
print("===================")
ans=input("Search More ? (Y)")
OUTPUT :

Enter Employee Number:102


Enter Employee Name:Ajay
Enter Employee Salary:45000
## Data Saved...##
Add More?n
Enter Employee Number to search:101
===================
Name : shiksha
Salary : 56000
Enter Employee Number to search:102
===================
Name : Sonia
Salary :
50000
Enter Employee Number to search:103
===================
Name : deep
Salary : 60000
Enter Employee Number to search:108
===================
EMPNO NOT FOUND
===================
Search More ? (Y) n
15. Write a python program to implement python Mathematical
functions. # Find GCD of the given two numbers using math module.

import math

num1=int(input("Enter the First Number:"))


num2=int(input("Enter the Second
Number:"))

GCD=math.gcd(num1,num2)

print("The GCD or Greatest Common Divisor of given two numbers:",GCD)

OUTPUT:

Enter the First Number:4


Enter the Second Number:8
The GCD or Greatest Common Divisor of given two numbers: 4

Enter the First Number:3


Enter the Second Number:9
The GCD or Greatest Common Divisor of given two numbers: 3
16. Write a python program to implement python String functions.

# Write a program to accept a string and display the following 1. no. of uppercase
characters # 2. no. of lowercase characters 3. no. of alphabets. 4. no. of digits

str1=input("Enter a string:")
ucount=lcount=dcount=0 #Initialise
for ch in str1: # Select the characters one by one from the
string if ch.isupper(): # if it is uppercase
ucount=ucount+1 # increment
elif ch.islower():
lcount=lcount+1
elif ch.isdigit():
dcount=dcount+1
print(ucount," ",lcount," ",ucount+lcount," ",dcount)

OUTPUT:

Enter a
string:123Python 1 5
6 3

Enter a string:STRING Functions


12345 7 8 15 5
17. Write a python program to make user defined module and import same in another
module or program.

# create summodule.py and define three functions in it.


def sum_series(n):
sum=0
for i in range(1,n+1):
sum=sum+i
return sum

def
sum_odd(n)
: sum=0
for i in range(1,n+1,2):
sum=sum+i
return sum

def sum_even(n):
sum=0
for i in range(2,n+1,2):
sum=sum+i
return sum

# create sum.py and import summodule in

it. import summodule

print(summodule.sum_series(10))
print(summodule.sum_odd(10))
print(summodule.sum_even(10))

OUTPUT:

35
15
20
18. Integrate SQL with Python by importing the MYSQL module to create a table
Employee. '''Program to create a table Employee with the following Structure:
Empno int primary
key, Ename
varchar(15),
Dept

varchar(15), Sal
int
Display the structure of the table after creation'''

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123")
# to check connection
if
mydb.isconnected()==Tru
e: print("Connection
ok")
else:
print("Error connecting to mysql database")
mycursor=mydb.cursor()
mycursor.execute("Drop Database If Exists Company")
mycursor.execute("CREATE DATABASE COMPANY")
print("Database Created")
mydb.close()
# To Create Table.
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123",
database="C ompany")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE EMP(EMPNO INTEGER(3), ENAME VARCHAR(20),
DEPT VARCHAR(15), SAL INT)")
print(“Table Created”)
mycursor.execute("DESC
Emp") for row in mycursor:
print(row
)
mydb.close()

OUTPUT:

Connection ok
Database
Created Table
created
('EMPNO', 'int(3)', 'YES', '', None, '')
('ENAME', 'varchar(20)', 'YES', '', None, '')
('DEPT', 'varchar(15)', 'YES', '', None, '')
('SAL', 'int(11)', 'YES', '', None, '')
19.Integrate SQL with Python by importing the MYSQL module to Insert records in
Employee.

'''Program to Insert 5 records into the table Employee with the following
Structure: Empnoint primary key,
Ename varchar(15),
Dept
varchar(15), Sal
int
Display the table content after insertion'''

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123",database="C
ompany")
mycursor=mydb.cursor()
# To insert multiple records
n=int(input("Enter how many records u want to
enter")) for i in range(n):
eno=int(input("Enter the Employee Number:"))
name=input("Enter the Employee Name:")
dname=input("Enter the Department Name:")
sal=int(input("Enter the Employee Salary:"))
query="Insert into Emp values({},'{}','{}',
{})".format(eno,name,dname,sal) mycursor.execute(query)

mydb.commit()
mycursor.execute("Select * from
Emp") for row in mycursor:
print(row
) mydb.close()

OUTPUT:

Enter how many records u want to enter:3


Enter the Employee Number:101
Enter the Employee Name:op Sharma
Enter the Department Name:Sales
Enter the Employee Salary:50000
Enter the Employee Number:102
Enter the Employee Name:jiya Verma
Enter the Department Name:Admin
Enter the Employee Salary:70000
(101, 'op Sharma', 'Sales', 50000)
(102, 'jiya Verma', 'Admin', 70000)
20. Integrate SQL with Python by importing the MYSQL module to search an employee
using Empno and if present in table display the record, if not display appropriate
message.

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123",database="Com
pany")
if
mydb.is_connected()==T
rue: print("Connection
ok")
else:
print("Error connecting to mysql database")
mycursor=mydb.cursor()
eno=int(input("Enter the Employee Number to search:"))
mycursor.execute("select * from Emp where
Empno={}".format(eno)) rs=mycursor.fetchall()
for row in rs:
if
row[0]==eno
:
print(row)
else:
print("Record not found")

OUTPUT:

Connection ok
Enter the Employee Number to Search:101
(101, 'Amit Sharma', 'Sales', 80000)

Connection ok
Enter the Employee Number to Search:102
(102, 'Diya Verma', 'Admin', 70000)
21. Integrate SQL with Python by importing the MYSQL module to search a Employee using
Empno, update the record.

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123",
d atabase="Company")
if
mydb.is_connected()==T
rue: print("Connection
ok")
else:
print("Error connecting to mysql database")
mycursor=mydb.cursor()
eno=int(input("Enter the Employee Number to search:"))
query="update Emp set sal=80000 where
Empno={}".format(eno) mycursor.execute(query)
mydb.commit()
mycursor.execute("Select * from
Emp") for row in mycursor:
print(row)
mydb.close()
print("Row updated Successfully")

OUTPUT:

Connection ok
Enter the Employee Number to search:101
(101, 'Amit Sharma', 'Sales', 80000)
(102, 'Diya Verma', 'Admin', 70000)
Row updated Successfully
22. Integrate SQL with Python by importing the MYSQL module to search a Employee using
Empno and if present in table delete the record.

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123",
d atabase="Company")
if
mydb.is_connected()==T
rue: print("Connection
ok")
else:
print("Error connecting to mysql database")
mycursor=mydb.cursor()
eno=int(input("Enter the Employee Number to
search:")) query="Delete from Emp where
Empno={}".format(eno) mycursor.execute(query)
mydb.commit()
mycursor.execute("Select * from
Emp") for row in mycursor:
print(row)
mydb.close()
print("Row deleted Successfully")

OUTPUT:

Connection ok
Enter the Employee Number to
search:101 Row deleted Successfully.

Connection ok
Enter the Employee Number to
search:102 Row deleted Successfully.
SQL QUERIES

1. Create a database gvpsschool, student table and insert data.Display the


data

mysql> create database gvpsschool;


Query OK, 1 row affected (1.31 sec)

mysql> use gvpsschool;


Database changed

mysql> create table student


-> (Rollno int primary key,
-> Name varchar(15),
-> Marks decimal(5,2));
Query OK, 0 rows affected (2.52 sec)

mysql> desc student;


+ + + + + + +
| Field | Type | Null | Key | Default | Extra |
+ + + + + + +
| Rollno | int | NO | PRI | NULL | |
| Name | varchar(15) | YES | | NULL | |
| Marks | decimal(5,2) | YES | | NULL | |
+ + + + + +
+ 3 rows in set (0.55 sec)

mysql> Insert into student


values(1,"Kriti",98); Query OK, 1 row affected
(0.19 sec)

mysql> Insert into student


values(2,"Preeti",95.2); Query OK, 1 row affected
(0.15 sec)

mysql> Insert into student values(3,"Neha


Tandon",94,898976453); Query OK, 1 row affected (0.12 sec)

mysql> Insert into student values(4,"Arpita Saha",90,678565652);


Query OK, 1 row affected (0.15 sec)

mysql> Insert into student values(5,"Ujjwal


Dagar",80,456234762); Query OK, 1 row affected (0.12 sec)
mysql> select * from student;
+ + + + +
| Rollno | Name | Marks | phoneno |
+ + + + +
| 1 | jyoti | 98.00 | 999999123 |
| 2 | Preet | 95.20 | 899945124 |
| 3 | Neha | 94.00 | 897987689 |
| 4 | Arpit | 90.00 | 678564526 |
| 5 | prerna Dagar | 80.00 | 456237789 |
+ + + +
+ 5 rows in set (0.00 sec)

mysql> select * from student where rollno=3;


+ + + + +
| Rollno | Name | Marks | phoneno |
+ + + + +
| 3 | Neha | 94.00 | 897987689 |
+ + + +
+ 1 row in set (0.05 sec)

mysql> select * from student where marks>95;


+ + + + +
| Rollno | Name | Marks | phoneno |
+ + + + +
| 1 | jyoti | 98.00 | 999999123 |
| 2 | Preet | 95.20 | 899945124 |
+ + + +
+ 2 rows in set (0.04 sec)

Implement the following SQL commands on the student table:

2. ALTER table to add new attributes/modify data type/drop

attribute. mysql> Alter table student add phoneno int(10);


Query OK, 0 rows affected, 1 warning (2.08 sec)
Records: 0 Duplicates: 0 Warnings: 1
mysql> Desc student;
+ + + + + + +
| Field | Type | Null | Key | Default | Extra |
+ + + + + + +
| Rollno | int | NO | PRI | NULL | |
| Name | varchar(15) | YES | | NULL | |
| Marks | decimal(5,2) | YES | | NULL | |
| phoneno | int | YES | | NULL | |
+ + + + + +
+ 4 rows in set (0.08 sec)

mysql> select * from student;


+ + + + +
| Rollno | Name | Marks | phoneno |
+ + + + +
| 1 | jyoti | 98.00 | NULL |
| 2 | Preet | 95.20 | NULL |
| 3 | Amit | 94.50 | NULL |
+ + + +
+ 3 rows in set (0.04 sec)

3. UPDATE table to modify data.


mysql> update student set phoneno=999999345 where
rollno=1; Query OK, 1 row affected (0.14 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> update student set phoneno=899999346 where


rollno=2; Query OK, 1 row affected (0.17 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> update student set phoneno=699999946 where
rollno=3; Query OK, 1 row affected (0.26 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from student;
+ + + + +
| Rollno | Name | Marks | phoneno |
+ + + + +
| 1 | Kriti | 98.00 | 999999345 |
| 2 | Preeti | 95.20 | 899999346 |
| 3 | Amit | 94.50 | 699999946 |
+ + + +
+ 3 rows in set (0.00 sec)
4. ORDER BY to display data in ascending / descending order.

mysql> select * from student order by name;


+ + + + +
| Rollno | Name | Marks | phoneno |
+ + + + +
| 4 | Arpita Saha | 90.00 | 678565652 |
| 1 | Kriti | 98.00 | 999999345 |
| 3 | Neha Tandon | 94.00 | 898976453 |
| 2 | Preeti | 95.20 | 899999346 |
| 5 | Ujjwal Dagar | 80.00 | 456234762 |
+ + + +
+ 5 rows in set (0.03 sec)

mysql> select * from student order by name desc;


+ + + + +
| Rollno | Name | Marks | phoneno |
+ + + + +
| 5 | Ujjwal Dagar | 80.00 | 456234762 |
| 2 | Preeti | 95.20 | 899999346 |
| 3 | Neha Tandon | 94.00 | 898976453 |
| 1 | Kriti | 98.00 | 999999345 |
| 4 | Arpita Saha | 90.00 | 678565652 |
+ + + +
+ 5 rows in set (0.00 sec)

5. DELETE to remove tuple(s).

mysql> Delete from student where Rollno=3;


Query OK, 1 row affected (3.09 sec)

mysql> select * from student;


+ + + + +
| Rollno | Name | Marks | phoneno |
+ + + + +
| 1 | Kriti | 98.00 | 999999345 |
| 2 | Preeti | 95.20 | 899999346 |
+ + + +
+ 2 rows in set (0.08 sec)
6. GROUP BY and find the min, max, sum, count and
average. Similar exercise may be framed for other cases.

i) To display details of all items in the stock table in ascending order


of stockdate.
Ans i) select * from stock order by stockdate;

ii) To display itemno and item name of those items from stock table
whose unit price is more than 10 rupees.
Ans ii) select itemno, item from stock where unitprice>10;

iii) To display details of those items whose dealer code (Dcode) is 102
or quantity in stock (qty) is more than 100 from stock table.
Ans iii) select * from stock where dcode=102 or qty>100;

iv) To display maximum unitprice of items for each dealer individually as


per Dcode from table stock.
Ans iv) select dcode, max(unitprice) from stock group by dcode;

v) Select count(distinct dcode) from


stock; Ans v) count(distinct dcode)
3
vi) Select qty*unitprice from stock where
itemno=5006; Ans vi) qty*unitprice
4400
vii) Select min(stockdate) from
stock; Ans vii) Min(stockdate)
01-Jan-09

viii) Increase the unit price of all the items by


Rs10. Ans viii) update stock set unitprice =
10+unitprice ;
ix) Display the sum of quantities of items from stock table as per
dcode. Ans ix) select dcode, sum(qty) from stock group by dcode;

x) Select * from stock where year(stockdate) >


2010; Ans x) Empty set

i) To display the name of all activities with their Acodes in descending


order. Ans i) select acodes, activityname from activity order by acode
desc;

ii) To display sum of prizemoney for each of the number of


participants groupings (as shown in column participantsnum 10,12,16).
Ansii) select sum(prizemoney) from activity groupby participantsnum having
participantsnum in(10,12,16);

iii) To display the coach’s name and acodes in ascending order of acode
from table coach.
Ans iii) select name, acode from coach order by acode;

iv) To display the content of activity table whose ScheduleDate is


earlier than 01/01/2004 in ascending order of participantsnum.
Ans iv) select * from activity where scheduledate < 01/01/2004 order
by participantsnum;

v) To display acode with their respective activity names and names of


the coaches from the two tables.
Ans v) select activity.acode, activity.activityname, coach.name from
activity, coach where activity.acode = coach.acode ;
vi) To display average prize money.
Ans vi) select avg(prizemoney) from activity;

vii) To increase the prize money by 100 rupees.


Ans vii) update activity set prizemoney= prizemoney+100 ;

viii) To display acode with their respective prizemoney in range 9000 to


16000 (both including).
Ans viii) select acode, prizemoney from activity where prizemoney between
9000 and 16000;

ix) To display names of coaches who have an ‘a’ in between their


names. Ans ix) select name from coach where name like “%a%”;

x) To display content of activity where acode has no


value. Ans x) select * from activity where acode is null;

xi) Select count(distinct participantsnum) from


activity; Ans xi) count (distinct participantsnum)
3
xii) Select max(scheduledate), min(scheduledate) from activity;
Ans xii) 19-Mar-2004, 12-Dec-2003

xiii) Select sum(prizemoney) from activity;


Ans xiii) 54000

xiv) Select distinct(participantsnum) from activity;


Ans xiv) 16, 10, 12
xv) Select count(*) from coach where
acode=1001; Ans xv) 2

You might also like