Practical File 2023-2024 Final

You might also like

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

CLASS – XII COMPUTER SCIENCE

PRACTICAL FILE – [2023 – 2024]


S.NO DATE NAME OF THE EXPEIMENT PAGE SIGNATUE
NO OF THE
TEACHER
1 ARITHMETIC OPERATIONS 1
2 FIBONACCI SERIES 5
3 FACTORIAL 9
4 STRING PALINDROME 13
5 PRIME NUMBER 17
6 SUM OF ALL ELEMENTS OF A LIST 21
7 MATHEMATICAL FUNCTIONS 25
8 RANDOM NUMBER 29
9 READ TEXT FILE LINE BY LINE AND SEPARATE BY ‘#’ 33
10 COPYING LINES TO TEXT FILE 37
TO DISPLAY NO OF VOWELS / CONSONANTS /
11 41
LOWERCASE AND UPPERCASE LETTERS
12 BINARY FILE TO STORE AND DISPLAY NAME 45
13 UPDATING BINARY FILE 51
14 CSV FILE – SEARCHING PASSWORD FOR GIVEN ID 57
15 CREATING CSV FILE 63
16 STACK IMPLEMENTATION 69
17 PYTHON PROGRAM TO CONNECT WITH DATABASE 75
TO CONNECT WITH DATABASE AND SEARCH EMPLOYEE
18 81
NO
TO CONNECT WITH DATABASE AND UPDATE EMPLOYEE
19 85
RECORD
TO CONNECT WITH DATABASE AND DELETE THE
20 91
RECORD
21 SQL COMMANDS EXERCISE – I 97
22 SQL COMMANDS EXERCISE – II 99
23 SQL COMMANDS EXERCISE – III 103
24 SQL COMMANDS EXERCISE - IV 109
EX.NO: 1
DATE: ARITHMETIC OPERATIONS
Creating a menu driven program to perform arithmetic operations
AIM:
To write a menu driven Python program to perform Arithmetic operations (+, -, *, /) based
on the user’s choice.
ALGORITHM:
Step 1: Start the execution of the program
Step 2: Input the variable opt, a and b
Step 3: If choice==1, calculate c=a+b
Step 4: If choice==2, calculate c=a-b
Step 5: If choice==3, calculate c=a*b
Step 6: If choice ==4, calculate c=a/b, check condition if b==0, enter any number other than
0, else print the divided value
Step 7: If any other choice is given print Invalid option
Step 8: Stop the execution of the program
SOURCE CODE:
print("1. Addition")
print("2.Subtraction")
print("3.Multiplication")
print("4. Division")
opt=int(input("Enter your Choice: "))
a=int(input("Enter the First Number: "))
b=int(input("Enter Second Number: "))
if opt==1:
c=a+b
print("The Addition of two number is: ",c)
elif opt==2:
c=a-b
print("The Subtraction of two number is: ",c)
elif opt==3:
c=a*b
print("The Multiplication of two number is :",c)
elif opt==4:
if b==0:
print("Enter any two number other than 0")
else:
c=a/b
print("The Division of two number is:",c)
else:
print("Invalid Option")

RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 2
DATE: FIBONACCI SERIES
Write a Python program to display Fibonacci series up to ‘n’ numbers.
AIM:
To write a Python program to display Fibonacci series up to ‘n’ numbers.
ALGORITHM:
Step 1: Start the program execution
Step 2: Initialize First=0, Second=1
Step 3: Read the value of no
Step 4: if no<=0 then enter positive integer
Step 5: Print first and second value then iterate through for loop and
calculate third = first + second
Step 6: Then assign first=second and second = third and print third
Step 7: Stop the program execution
SOURCE CODE:
First =0
Second =1
no=int(input("How many Fibonacci Numbers you want to display: "))
if no<=0:
print("Please Enter Positive Integer")
else:
print(First)
print(Second)
for i in range(2,no):
Third=First + Second
First = Second
Second = Third
print(Third)

RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 3
DATE: FACTORIAL
Write a Python program to find the factorial value for the given number.
AIM:
To find the factorial value for the given number.
ALGORITHM:
Step 1: Start the program execution
Step 2: Read the value of number
Step 3: Call the function factorial(number)
Step 4: Initialize fact=1
Step 5: Iterate through for loop, if the condition is true.
Step 6: Calculate fact = fact*i
Step 7: Return fact to result
Step 8: Print result
Step 9: Stop the program execution
SOURCE CODE:
def factorial(num):
fact=1
for i in range(1,num+1):
fact=fact*i
return fact
n=int(input("Please enter any number to find factorial: "))
result=factorial(n)
print("The factorial of ", n , "is: ", result)

RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 4
DATE: STRING PALINDROME
Write a program in Python to find given string is palindrome or not.
AIM:
To check whether the given string is Palindrome or not.
ALGORITHM:
Step 1: Start the program execution
Step 2: Read the value
Step 3: Iterate through for loop
Step 4: Check condition, if str[i]!=str[len(str)-i-1]
Step 5: Return False to ans
Step 6: Return True to ans
Step 7: Check if (ans), if the condition is true
Step 8: If true print “The given string is Palindrome”
Step 9: Else print “ The given string is not a Palindrome”
Step 10: Stop the program execution
SOURCE CODE:
def isPalindrome(str):
for i in range(0,int(len(str)/2)):
if str[i]!=str[len(str)-i-1]:
return False
else:
return True
s=input("Enter String: ")
ans=isPalindrome(s)
if(ans):
print("The given string is Palindrome")
else:
print("The given string is not a Palindrome")

RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 5
DATE: PRIME NUMBER
Write a Python program to check whether the given number is prime no or not.
AIM:
To write a Python program to find whether the entered number is Prime or not.
ALGORITHM:
Step 1: Start the program execution
Step 2: import math
Step 3: Input a number
Step 4: Iterate through, for i in range(2,int(math.sqrt(num))+1)
Step 5: Check condition if num%i==0
Step 6: Set flag = False, if is prime
Step 7: Print number is prime else number is not prime number
Step 8: Stop the program execution
SOURCE CODE:
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")

RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 6
DATE: SUM OF ALL ELEMENTS OF A LIST
Write recursive function to find the sum of all elements of a list.
AIM:
To write a recursive function to find the sum of all elements of a list.
ALGORITHM: [ Driver code: main() ]
Step 1: Start the program execution
Step 2: Read no and create empty array
Step 3: Check condition insert element and append element to the list
Step 4: Print items in the list
Step 5: To print sum of elements in the list call function and execute the statement
Step 6: Print the answer
Step 7: Stop the program execution
Recursive function : sum_arr(arr,size):
Step 1: Start the program execution.
Step 2: if size ==0 then return 0.
Step 3: else return arr[size-1] + sum_arr(arr,size-1)
SOURCE CODE:
def sum_arr(arr,size):
if(size==0):
return 0
else:
return arr[size-1]+sum_arr(arr,size-1)
#Driver code : Main program
def main():
n=int(input("Enter the number of elements in the list:"))
a=[]
for i in range(0,n):
element=int(input("Enter Element:"))
a.append(element)
print("The List is:")
print(a)
print("The Sum of items in list:")
b=sum_arr(a,n) # calling a function
print(b)
main()

RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 7
DATE: MATHEMATICAL FUNCTIONS
Write a Python program to implement mathematical functions.
AIM:
To write a Python program to implement mathematical functions to find:
i) Square of a Number.
ii) Log of a Number (i.e log10)
iii) Quad of a Number.
ALGORITHM:
Step 1: Start the program execution
Step 2: import math module
Step 3: Define Square(num) and calculate by math.Square(num,2)
Step 4: Define log(num) and calculate math.log10(num)
Step 5: Define Quad(X,Y), and calculate math.sqrt(X**2)+(Y**2)
Step 6: Print statement to print all values
Step 7: Stop the program execution
SOURCE CODE:
import math
def Square(num):
S=math.pow(num,2)
return S
def Log(num):
S=math.log10(num)
return S
def Quad(X,Y):
S=math.sqrt(X**2 +Y**2)
return S
print("The Square of a Number is:",Square(5))
print("The Log of a Number is:",Log(10))
print("The Quad of a Number is:",Quad(5,2))

RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 8
DATE: RANDOM NUMBER
Write a Python program to generate random number between 1 to 6 to simulates the dice
AIM:
To write a Python program to generate random number between 1 to 6 to simulates the
dice.
ALGORITHM:
Step 1: Start the program execution
Step 2: import random module
Step 3: while condition is True
Step 4: Input choice (y/n)
Step 5: If choice is ‘y’ then no= random.randint(1,6), generate any of the number from 1 to 6
and store in no
Step 6: Print the no else break
Step 7: Stop the program execution
SOURCE CODE:
import random
while True:
Choice=input("\n Do you want to roll the dice (y/n):")
no=random.randint(1,6)
if Choice=='y':
print("\n Your Number is:",no)
else:
break

RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 9
DATE: READ TEXT FILE LINE BY LINE AND SEPARATE BY ‘#’
Write a Python program to read a text file line by line and display each word separated by ‘#’.
AIM:
To write a Python program to Read a text file “Story.txt” line by line and display each word
separated by ‘#’.
ALGORITHM:
Step 1: Start the program execution
Step 2: open Story.txt in read mode and readlines from Story.txt
Step 3: Check for loop, if the condition is true
Step 4: Split words in line using split() function
Step 5: Iterate through for loop, if the condition is true
Step 6: print the value of i and add ‘#’ symbol
Step 7: Stop the program execution
SOURCE CODE:
f=open("Story.txt")
Contents=f.readlines()
for line in Contents:
words=line.split()
for i in words:
print(i+'#',end= ' ')
print(")
f.close()

RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 10
DATE: COPYING LINES TO TEXT FILE
Write a Python program to copy all the lines that contains the character ‘a’ in a file and copy
it to another file.
AIM:
To write a Python program to copy all the lines that contains the character ‘a’ in a file and
copy it to another file.
ALGORITHM:
Step 1: Start the program execution
Step 2: open ‘Sample.txt’ in read mode and ‘New.txt’ in write mode
Step 3: Check for line in F1, if the condition is true, if Line[0]==’a’ or Line[0]==’A’
Step 4: If true then write that line in F2
Step 5: Print File copied successfully
Step 6: close files F1 and F2
Step 7: Stop the program execution
SOURCE CODE:
F1=open("Sample.txt",'r')
F2=open("New.txt",'w')
for Line in F1:
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")
F1.close()
F2.close()

RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 11
DATE : TO DISPLAY NO OF VOWELS / CONSONANTS / LOWERCASE AND UPPERCASE LETTERS
Write a Python program to Read a text file and display the number of Vowels/ Consonants /
Uppercase / Lowercase characters in the file.
AIM:
To write a Python program to read a text file and display the numbers of vowels/
consonants / uppercase / Lowercase characters in the file.
ALGORITHM:
Step 1: Start the program execution
Step 2: Open text file in read mode using open() method
Step 3: Read the content of the file using read() method
Step 4: Write the logic for counting the Vowels, Consonants, Upper case, Lower case letters
using islower() , isupper(). Ch in [‘a’, ’e’ .’I’ ,’o’, ’u’], ch in [‘b’, ’c’, ’d’, ’f’, ’g’, ’h’, ’j’, ’k’,
’l’ ,’m’, ’n’ ,’p’, ’q’, ‘r’,,’s’, ‘t’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’]
Step 5: Close the file using close() method
Step 6: Print the counted data
Step 7: Stop the program execution
SOURCE CODE:
f=open("Story.txt",'r')
Contents=f.read()
Vowels = Consonants = Lower_case = Upper_case=0
for ch in Contents:
if ch in 'aeiouAEIOU':
Vowels=Vowels+1
if ch in 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ':
Consonants=Consonants+1
if ch.islower():
Lower_case=Lower_case+1
if ch.isupper():
Upper_case=Upper_case+1
f.close()
print("The total numbers of vowels in the file:",Vowels)
print("The total numbers of Consonants in the file:",Consonants)
print("The total numbers of Uppercase letters in the file:",Upper_case)
print("The total numbers of Lowercase letters in the file:",Lower_case)

RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 12
DATE : BINARY FILE TO STORE AND DISPLAY NAME
Write Python program to 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.
AIM:
To write a Python program to create binary file to store and display name.
ALGORITHM:
Step 1: Start the program execution
Step 2: Import the pickle module and open the file ‘student.dat’ in write mode
Step 3: Create list student= [], using dump function write the students details to binary file
Step 4: Close the file
Step 5: Open the file “Student.dat” in read mode
Step 6: Using load function read the student details
Step 7: Iterate through for loop and check condition if S[0]==r, then go to next step
Step 8: Print name and set found =True
Step 9: Print “ Record Found”, if not found print “Sorry Roll number not found”
Step 10: Close the file and stop the program execution
SOURCE CODE:
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()
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("#p###Sorry! Roll number not found ####")
ans=input("Search more ?(Y) :")
f.close()
RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 13
DATE : UPDATING BINARY FILE
Write Python program to Create a binary file with roll number, name and marks. Input a roll
number and update the marks.
AIM:
To write a program to create binary file and update details.
ALGORITHM:
Step 1: Start the program execution
Step 2: Import the pickle module and open the file ‘student.dat’ in write mode
Step 3: Create list student= [], using dump function write the students details to binary file
Step 4: Close the file
Step 5: Open the file “Student.dat” in read mode
Step 6: Using load function read the student details from binary file
Step 7: Update student mark if the condition is True
Step 8: Print “Record Updated” and set found=True
Step 9: If not found print “Sorry! Roll number not found”
Step 10: Close the file and Stop the program execution
SOURCE CODE:
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
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 update :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
print("## Current Marks is :",s[2]," ##")
m = int(input("Enter new marks :"))
s[2]=m
print("## Record Updated ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Update more ?(Y) :")
f.close()
RESULT:
Thus, the given program is executed successfully and the output is verified.
EX.NO: 14
DATE : CSV FILE – SEARCHING PASSWORD FOR GIVEN ID
Write program to Create a CSV file by entering user-id and password, read and search the
password for given user id.
AIM:
To write a program to create a CSV file by entering User-id and Password, read and search
the password for given user-id.
ALGORITHM:
Step 1: Start the program execution
Step 2: Import the CSV module, create list with user id and password, and open the file
‘userinformation.csv”, in write mode
Step 3: csv.writer() returns a writer object which writes data into CSV file
Step 4: Use writerobject.writerow() (or) writerobject.writerows() to write one row or
multiple rows of data onto the writer object
Step 5: csv.reader() returns a reader object which loads data from CSV file
Step 6: Get the user-id from the user
Step 7: Check userid which is in CSV file is equal to the records[0]
Step 8: If the condition is True, print password and set flag= False
Step 9: if flag print “User-id not found”
Step 10: Stop the program execution
SOURCE CODE:
import csv
list=[["user1","password1"],["user2","password2"],["user3","password3"],["user4",
"password4"],["user5","password5"]]
F1=open("userinformation.csv",'w',newline="\n")
writer=csv.writer(F1)
writer.writerows(list)
F1.close()
F2=open("userinformation.csv","r")
rows=csv.reader(F2)
userid=input("Enter User Id:")
flag=True
for records in rows:
if records[0]==userid:
print("The password is:",records[1])
flag = False
break
if flag:
print("User-Id not Found")

RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 15
DATE : CREATING CSV FILE
Write a Python program to create and search employee’s record in CSV file.
AIM:
To 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.
ALGORITHM:
Step 1: Start the program execution
Step 2: import the CSV module and open the file “emp.csv” in append mode
Step 3: csv.writer() returns a writer object which writes data into CSV file
Step 4: Use writerobject.writerow() to write one row of data onto the writer object
Step 5: csv.reader() returns a reader object which loads data from CSV file
Step 6: iterate through for loop and check condition if data[0]==str(no), if true display name
and salary
Step 7: if found ==0, print “The searched employee number is not found”
Step 8: close the file and stop the program execution
SOURCE CODE:
import csv
def Create():
F=open("Emp.csv",'a',newline='')
W=csv.writer(F)
opt='y'
while 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='')
no=int(input("Enter Employee Number to Search"))
found=0
row=csv.reader(F)
for data in row:
if data[0]==str(no):
print("\n Employee Details 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()
RESULT:
Thus, the given program is executed successfully and the output is verified.
EX.NO: 16
DATE : STACK IMPLEMENTATION
Write a Python program to implement Stack using a list.
AIM:
To write a Python program to implement Stack using a list.
ALGORITHM:
Step 1: Start the program execution
Step 2: Read the value of choice
Step 3: Check if opt==1, then call the function PUSH() – To insert an element in stack and
append the value
Step 4: Check if opt==2, then call the function POP() – To delete an element from stack using
stack.pop()
Step 5: Check if opt==3, then call the function PEEK() – To display top element of stack
Step 6: Check if opt==4, then call the function Disp() – To view the element in stack
Step 7: If any other choice print “Invalid Choice”
Step 8: Stop the program execution
SOURCE CODE:
def PUSH():
ele=int(input("Enter the element which you want to post:"))
Stack.append(ele)
def POP():
if Stack==[]:
print("Stack is Empty/Underflow")
else:
print("The Deleted Element is:",Stack.pop())
def PEEK():
top=len(Stack)-1
print("The Top Most Element of the Stack is:",Stack[top])
def Disp():
top=len(Stack)-1
print("The Stack Elements Are:")
for i in range(top,-1,-1):
print(Stack[i])
# Main Program
Stack=[]
opt='y'
while opt=='y' or opt=='Y':
print("Stack Operations")
print("****************")
print("1. PUSH")
print("2. POP")
print("3.PEEK")
print("4.DISPLAY")
print("****************")
opt=int(input("Enter your choice:"))
if opt==1:
PUSH()
elif opt==2:
POP()
elif opt==3:
PEEK()
elif opt==4:
Disp()
else:
print("Invalid Input")
opt=input("Do you want to perform another stack operation(y/n)?:")

RESULT:
Thus, the given program is executed successfully and the output is verified.
EX.NO: 17
DATE:
PYTHON PROGRAM TO CONNECT WITH DATABASE
Write program to connect with database and store record of employee and display records.
AIM:
To write a Python program to connect with database and store record of employee and
display records.
ALGORITHM:
Step 1: Start the program execution
Step 2: In command prompt set Python path and install MySQL connector
[pip install mysql-connector-python]
Step 3: To check if the installation was successful, go to Python IDLE and run the given code ,
import mysql.connector.
Step 4: Use the connect() method
Step 5: Use the cursor() method
Step 6: Use the execute() method
Step 7: Extract result using fetchall()
Step 8: Close cursor and connection objects
Step 9: Stop the program execution
SOURCE CODE:
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin")
cur = con.cursor()
cur.execute("create database if not exists company")
cur.execute("use company")
cur.execute("create table if not exists employee(empno int, name varchar(20), dept
varchar(20),salary int)")
con.commit()
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
choice = int(input("Enter Choice :"))
if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
elif choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()
print("EMPNO","NAME","DEPARTMENT","SALARY")
for row in result:
print(row[0],row[1],row[2],row[3])
elif choice==0:
con.close()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")

RESULT:
Thus, the given program is executed successfully and the output is verified.
EX.NO: 18 PYTHON PROGRAM TO CONNECT WITH DATABASE AND SEARCH EMPLOYEE NO
DATE:
Write program to connect with database and search employee number in table employee and
display record of empno, not found display appropriate message.
AIM:
To write a Python program to connect with database and search in table and display record.
ALGORITHM:
Step 1: Start the program execution
Step 2: Install MySQL connector module
Step 3: Import MySQL connector module
Step 4: Use the connect() method
Step 5: Use the cursor() method
Step 6: Use the execute() method
Step 7: Extract result using fetchall()
Step 8: Close cursor and connection objects
Step 9: Stop the program execution
SOURCE CODE:
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin",database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("EMPNO", "NAME","DEPARTMENT","SALARY")
for row in result:
print(row[0],row[1],row[2],row[3])
ans=input("SEARCH MORE (Y) :")
RESULT:
Thus, the given program is executed successfully and the output is verified.

EX.NO: 19 PYTHON PROGRAM TO CONNECT WITH DATABASE AND UPDATE EMPLOYEE


RECORD
DATE:
Write program to connect with database and update the employee record of entered empno.
AIM:
To write a Python program to connect with database and update the employee record of
entered empno.
ALGORITHM:
Step 1: Start the program execution
Step 2: Install MySQL connector module
Step 3: Import MySQL connector module
Step 4: Use the connect() method
Step 5: Use the cursor() method
Step 6: Use the execute() method
Step 7: Extract result using fetchall()
Step 8: Close cursor and connection objects
Step 9: Stop the program execution
SOURCE CODE:
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin",database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE UPDATION FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO UPDATE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("EMPNO","NAME","DEPARTMENT","SALARY")
for row in result:
print(row[0],row[1],row[2],row[3])
choice=input("\n## ARE YOUR SURE TO UPDATE ? (Y) :")
if choice.lower()=='y':
print("== YOU CAN UPDATE ONLY DEPT AND SALARY ==")
print("== FOR EMPNO AND NAME CONTACT ADMIN ==")
d = input("ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO CHANGE )")
if d=="":
d=row[2]
try:
s = int(input("ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE ) "))
except:
s=row[3]
query="update employee set dept='{}',salary={} where empno={}".format(d,s,eno)
cur.execute(query)
con.commit()
print("## RECORD UPDATED ## ")
ans=input("UPDATE MORE (Y) :")
RESULT:
Thus, the given program is executed successfully and the output is verified.
EX.NO: 20 PYTHON PROGRAM TO CONNECT WITH DATABASE AND DELETE THE RECORD
DATE:
Write program to connect with database and delete the record of entered empno.
AIM:
To write a Python program to connect with database and delete the record.
ALGORITHM:
Step 1: Start the program execution
Step 2: Install MySQL connector module
Step 3: Import MySQL connector module
Step 4: Use the connect() method
Step 5: Use the cursor() method
Step 6: Use the execute() method
Step 7: Extract result using fetchall()
Step 8: Close cursor and connection objects
Step 9: Stop the program execution
SOURCE CODE:
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin",database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE DELETION FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("EMPNO","NAME", "DEPARTMENT","SALARY")
for row in result:
print(row[0],row[1],row[2],row[3])
choice=input("\n## ARE YOUR SURE TO DELETE ? (Y) :")
if choice.lower()=='y':
query="delete from employee where empno={}".format(eno)
cur.execute(query)
con.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")

RESULT:
Thus, the given program is executed successfully and the output is verified.

SQL COMMANDS
EXERCISE - I
Ex.No: 21
Date:
AIM: To write Queries for the following questions based on the given table:
ROLLNO NAME GENDER AGE DEPT DOA FEES
1 ARUN M 24 COMPUTER 1997-01-10 120
2 ANKIT M 21 HISTORY 1998-03-24 200
3 ANKU F 20 HINDI 1996-12-12 300
4 BALA M 19 NULL 1999-07-01 400
5 CHARAN M 18 HINDI 1997-09-05 250
6 DEEPA F 19 HISTORY 1997-02-27 300
7 DINESH M 22 COMPUTER 1997-02-25 210
8 USHA F 23 NULL 1997-07-31 200

a) Write a query to create a new database in the name of “STUDENTS”

b) Write a query to open the database “STUDENTS”

c) Write a query to create the above table called STU

d) Write a query to list all the existing database names.


SQL COMMANDS
EXERCISE - II
Ex.No: 22
Date:
AIM: To write Queries for the following questions based on the given table:
ROLLNO NAME GENDER AGE DEPT DOA FEES
1 ARUN M 24 COMPUTER 1997-01-10 120
2 ANKIT M 21 HISTORY 1998-03-24 200
3 ANKU F 20 HINDI 1996-12-12 300
4 BALA M 19 NULL 1999-07-01 400
5 CHARAN M 18 HINDI 1997-09-05 250
6 DEEPA F 19 HISTORY 1997-02-27 300
7 DINESH M 22 COMPUTER 1997-02-25 210
8 USHA F 23 NULL 1997-07-31 200

a) Write a query to select distinct Department from STU table.

b) To show all information about students of History department.

c) Write a query to list name of female students in Hindi Department.

d) Write a query to list all the tables that exists in the current database.

e) Write a query to insert all the rows of above table into STU table.

f) Write a query to display all the details of the Employees from the above table ‘STU’.

g) Write a query to display Rollno, Name and Department of the students from STU table.
SQL COMMANDS
EXERCISE – III
EX.NO:23
DATE:
AIM:
To write queries for the following questions based on the given table:

ROLLNO NAME GENDER AGE DEPT DOA FEES


1 ARUN M 24 COMPUTER 1997-01-10 120
2 ANKIT M 21 HISTORY 1998-03-24 200
3 ANKU F 20 HINDI 1996-12-12 300
4 BALA M 19 NULL 1999-07-01 400
5 CHARAN M 18 HINDI 1997-09-05 250
6 DEEPA F 19 HISTORY 1997-02-27 300
7 DINESH M 22 COMPUTER 1997-02-25 210
8 USHA F 23 NULL 1997-07-31 200

a) Write a query to delete the details of Roll number is 8.

b) Write a query to change the fees of students to 170 whose Roll number is 1, if the existing
fees is less than 130.

c) Write a query to list name of the students whose ages are between 18 to 20.

d) Write a query to display the name of the students whose name is starting with ‘A’.

e) Write a query to list the names of those students whose name have second alphabet ‘n’ in
their names.

f) Write a query to add a new column Area of type varchar in table STU.
-
g) Write a query to display Name of all students whose Area contains NULL.

h) Write a query to delete Area column from the table STU.

i) Write a query to delete table from database.


EX.NO : 24
DATE:
SQL COMMANDS
EXERCISE – IV
AIM:
To write queries for the following questions based on the given table:
TABLE : STOCK
PNO PNAME DCODE QTY UNITPRICE STOCKDATE
5005 BALL POINT PEN 102 100 10 2021-03-31
5003 GEL PEN PREMIUM 102 150 15 2021-01-01
5002 PENCIL 101 125 4 2021-02-18
5006 SCALE 101 200 6 2020-01-01
5001 ERASER 102 210 3 2020-03-19
5004 SHARPENER 102 60 5 2020-12-09
5009 GEL PEN CLASSIC 103 160 8 2022-01-19

TABLE : DEALERS
DCODE DNAME
101 SAKTHI STATIONERIES
103 CLASSIC STATIONERIES
102 INDIAN BOOK HOUSE

a) To display the total Unit price of all products whose Dcode is 102.

b) To display details of all products in the stock table in descending order of stock date.

c) To display maximum unit price of products for each dealer individually as per dcode from
the table Stock.

d) To display the Pname and Dname from table stock and dealers.

RESULT:
Thus, the given queries are executed successfully and the output is verified.

You might also like