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

practical file class xii cs(2024-25)

Uploaded by

shashiawasthi762
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

practical file class xii cs(2024-25)

Uploaded by

shashiawasthi762
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

INDEX PAGE

Section- A:- Python


PROGRAMS
Program 1: Program to enter two numbers and print the result of arithmetic operations like +,-,*,/, //
and %.
Program 2: Write a program to find whether an inputted number is perfect or not.
Program 3: Write a Program to check if the entered number is Armstrong or not.
Program 4: Write a Program to find factorial of the entered number.
Program 5: Write a Program to enter the number of terms and to print the Fibonacci Series.
Program 6: Input any number from user and check is it Prime no. or not
Program 7: Write a program to find the occurrence of any word in a string
Program 8: Program to perform logical operation on string.
Program 9: Write a menu driven program to check that the entered
string is a palindrome or not,to reverse the original string and to print each word of the original
string in reverse order.
Program 10: Program to implement all user defined functions of a list
Program 11: Program to show various logical operation on List.
Program 12: Program to show various logical operation on nested List
Program 13: Program to implement all user defined functions of Dictionary
Program 14: Program to create and read text file.
Program 15: Write a program to read content of file line by line and display each word separated
by '#'.
Program 16: Write a program to read content of fileand display total number of vowels, consonants,
lowercase and uppercase characters.
Program 17: Write a program to create a binary file to store Rollno andname Search for Rollno and
display record if found otherwise "Roll no. notfound".
Program 18: Program to create binary file to store Rollno,Name and Marks and update marks of
entered Rollno.
Program:19 Program to implement all operation on binary file.
Program 20: Program to write records of student in CSV file.
Program 21: Program to read data from csv file student.csv
Program 22: Program to write in a csv file using writerow() function and new delimiter ';'.
Program 23: Program to read data from csv file student.csv
Program 24: write a program to connect with database and display records of emp table.

1
Section-B :- MySQL
QUERIES ON DATABASE
1. Write an SQL Query to create a database Employee.
2. Write an SQL Query to open database Employee.
3. Write an SQL Query to create table empl.
4. Write an SQL Query to show the structure of the table.
5. Write an SQL Query to Insert 7 records as shown below:

6. Write an SQL Query to display all records from table empl.


7. Write an SQL Query to display EmpNo and Ename of all employees from the table empl.
8. Write an SQL Query to display Employees who earn more than 40000.
9. Write an SQL Query to display Employees who work as Accountant.
10. Write an SQL Query to add a column Commission to Table Empl.
11. Write an SQL Query to increase the Salary of all employees by 10% in the table empl.
12. Write an SQL Query to set commission as 5% of salary of Sales Executive.
13. Write SQL query to display Ename, Salary, and Salary added with comm from table empl.
14. Write an SQL Query to display the details of employees whose name have only five letters.
15. Write an SQL Query to display Empno, Ename, Salary, and Sal*12 as Annual Salary.
16. Write an SQL Query to display the name of employee whose name contains “r” as third
letter.
17. Write an SQL Query to display the name and salary of those employees whose salary is
between 35000 and 40000.
18. Write an SQL Query to change Ename ‘Sam’ by ‘Samuel’.
19. Write an SQL Query to display table data according to descending order of salary.
20. Display job wise total salary of employees using GROUP BY clause.
21. Write an SQL Query to delete entire table IF EXISTING.

2
Section - C (Python MySQL Connectivity)
PROGRAMS
Program 1:- Program to connect with database and store record of employee and display records.

Program 2:- Program to connect with database and update the employee record of entered empno.

Program 3:- Program to connect with database and search employee number in table employee and
display record, if empno not found display appropriate message.

Program 4:- Program to connect with database and delete the employee record of entered empno.

*********************************

3
Section-A ( PYTHON)
Program 1: Program to enter two numbers and print the result of arithmetic operations like +,-,*,/, // and %.

result =0
val1 = float(input("Enter the first value :"))
val2 = float(input("Enter the second value :"))
op = input("Enter any one of the operator (+,-,*,/,//,%)")
if op == "+":
result = val1 + val2
elif op == "-":
result = val1 - val2
elif op =="*":
result = val1 * val2
elif op =="/":
if val2 ==0:

print("Please enter a value other than 0") \


else:
result = val1 / val2
elif op == "//":
result = val1 // val2
else:
result = val1 % val2

print("The result is :",result)

4
OUTPUT

5
Program 2: Write a program to find whether an inputted number is perfect or not.

def pernum(num):
divsum=0
for i in range(1,num):
if num%i == 0:
divsum+=i
if divsum==num:
print('Perfect Number')
else:
print('Not a perfect number')

n=int(input("Enter a number to check whether it is a perfect number or not:"))


pernum(n)

OUTPUT

6
Program 3: Write a Program to check if the entered number is Armstrong or not.

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


no1 = no
sum = 0
while(no>0):
ans = no % 10;
sum = sum + (ans * ans * ans)
no = int (no / 10)
if sum == no1:
print("Armstrong Number")
else:
print("Not an Armstrong Number")

OUTPUT

7
Program 4: Write a Program to find factorial of the entered number.

num = int(input("Enter the number for calculating its factorial : "))


fact = 1
i=1
while i<=num:
fact = fact*i
i=i+1
print("The factorial of ",num,"=",fact)

OUTPUT

8
Program 5: Write a Program to enter the number of terms and to print the Fibonacci Series.

i =int(input("Enter the limit of Fibonacci Series:"))


x=0
y=1
z=1
print("Fibonacci series")
print(x, y,end= " ")
while(z<i):
print(z, end=" ")
x=y
y=z
z=x+y

OUTPUT

9
Program 6: Input any number from user and check is it Prime no. or not

num = int(input("Enter any number :"))


isPrime=True
for i in range(2,num//2+1):
if num % i == 0:
isPrime=False
if isPrime:
print("Number is Prime")
else:
print("Number is not Prime")

OUTPUT

10
Program 7: Write a program to find the occurrence 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

11
Program 8: Program to perform logical operation on string.

c=0
ch='y'
v=c=d=s=0
St = input("Enter a string -> ")
while ch == 'y' or ch=='Y':
print("1. Count no of spaces")
print("2. Count vowel,consonants, digit and special characters")
print("3. Count and display no of words starting with A or a ")
print("4. Longest word in a string ")
print("5. Display the word in which maximum time alpahbet e appear")
x = int(input("Enter choice = "))

if x == 1:
for i in St:
if i == ' ':
c=c+1
print("No of spaces = ",c)
if x == 2:
for i in range(len(St)):
if St[i] in "aeiouAEIOU":
v=v+1
elif St[i] in "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstuvwxyz":
c=c+1
elif St[i] in "0123456789":
d=d+1
else:
s=s+1
print("No of vowels ",v)
print("No of consonants ",c)
print("No of digits ",d)
print("No of special character",s)
if x == 3:
v=0
L = St.split()
print(L)
for i in range(len(L)):
if L[i][0] == 'A' or L[i][0] == 'a':
print(L[i])
v=v+1
12
print("No of words starting with A or a ",v)
if x == 4:
v=0
L = St.split()
print(L)
S=""
for i in range(len(L)):
if len(L[i])>v:
v = len(L[i])
S = L[i]
print("longest word ", S, " Length is ", v)
if x == 5:
v=0
L= St.split()
print(L)
S= " "
for i in range(len(L)):
m = L[i].count('e')
if m > v:
v=m
S = L[i]
print("Word ", S, " is containing e ", v, "times")
ch = input("\nDo you want to continue Y/N = ")

13
OUTPUT

14
Program 9: Write a menu driven program to check that the entered string is a palindrome or not, to reverse
the original string and to print each word of the original string in reverse order.

c=0
ch='y'
v=c=d=s=0

while ch == 'y' or ch=='Y':


print("1. Enter string ")
print("2. check it is palindrome or not")
print("3. create a string which is reverse of original string")
print("4. Print each word in reverse order ")
x = int(input("Enter choice = "))
if x == 1:
St = input("Enter a string -> ")
print("Entered string is -> ", St)
if x == 2:
L = len(St)
j = L-1
f=0
for i in range(L):
if St[i] != St[j]:
f=1
j=j-1
if f==1:
print("String is not palindrome")
else:
print("String is palindrome")

if x == 3:
L = len(St) - 1
St1 = ""
for i in range(L,-1,-1):
St1 = St1 + St[i]
print("Reversed string is ", St1)
if x == 4:
L = St.split()
x = len(L)
for i in L:
for j in range(len(i)-1, -1, -1):
print(i[j],end="")
print(end=" ")

ch = input("\nDo you want to continue Y/N = ")

15
OUTPUT

16
Program 10: Program to implement all user defined functions of a list

ch='y'
L = [1,2,3,4,2,3,2,4,5,6,71,1,10,12]
while ch == 'y' or ch=='Y':
print("1. append in list")
print("2. Insert in a list")
print("3. Find length of list")
print("4. To count occurence of an element")
print("5. Extend a list")
print("6. Find the sum of list elements")
print("7. Find the index of given element")
print("8. Find the minimum element in a list")
print("9. Find the maximum element in a list")
print("10.To pop element")
print("11.To remove element")
print("12.To use del ")
print("13.To reverse a list")
print("14.To sort a list")
x = int(input("Enter choice = "))
if x == 1:
print("Original list ", L)
val = int(input("Enter a value to be appended -> "))
L.append(val)
print("List after append ", L)
if x == 2:
val = int(input("Enter a value to be inserted -> "))
loc = int(input("Enter a location to insert -> "))
L.insert(loc,val)
print("Original list ", L)
print("List after insert ",L)
if x == 3:
n = len(L)
print("Length of list ",n)
if x == 4:
val = int(input("Enter a value whose occurence want to count -> "))
n = L.count(val)
print(val," occur ",n," times in list", L)
if x == 5:
M = [100,200,300,4000]

17
L.extend(M)
print("List after extend ",L)
if x == 6:
n = sum(L)
print("Sum of list elements ",n)
if x == 7:
print(L)
print("1. To give index when no stariing and ending value given")
print("2. To give index after given staring index value")
print("3. To give index after given staring and ending index value")
y = int(input("Enter choice -> "))
if y == 1:
val = int(input("Enter a value whose index you want -> "))
n = L.index(val)
print("index of ", val," is ", n)
if y == 2:
val = int(input("Enter a value whose index you want -> "))
loc = int(input("Enter a staring location -> "))
n = L.index(val,loc)
print("index of ", val," is ", n)
if y == 3:
val = int(input("Enter a value whose index you want -> "))
loc = int(input("Enter a staring location -> "))
end = int(input("Enter a ending location -> "))
n = L.index(val,loc,end)
print("index of ", val," is ", n)
if x == 8:
n = min(L)
print("Minimum element of list ",n)
if x == 9:
n = max(L)
print("Maximum element of list ",n)
if x == 10:
print("1. To pop last element ")
print("2. To pop a particular index")
y = int(input("Enter the choice"))
if y == 1:
print("List before pop ",L)
n = L.pop()
print("List after pop ",L)
if y == 2:
loc = int(input("Enter a location to pop -> "))
18
print("List before pop ",L)
n = L.pop(loc)
print("List after pop ",L)
if x == 11:
print("List before remove ",L)
val = int(input("Enter a value want to remove -> "))
L.remove(val)
print("List after remove ",L)
if x == 12:
print("1. To delete complete list")
print("2. To delete a particular element from list")
y = int(input("Enter the choice"))
if y == 1:
print("List before del ",L)
del L
print("List after del ",L)
if y == 2:
print("List before pop ",L)
loc = int(input("Enter a location of element to delete -> "))
del L[loc]
print("List after del ",L)
if x == 13:
print("List before reverse",L)
L.reverse()
print("List after reverse ",L)
if x == 14:
print("List before sort",L)
L.sort()
print("List in ascending order ",L)
L.sort(reverse=True)
print("List in descending order ",L)
ch = input("\nDo you want to continue Y/N = ")

19
OUTPUT

20
Program 11: Program to show various logical operation on List.

def search():
L = []
M = []
N= [ ]
n = int(input("Enter how many elements you want in the list"))

for i in range(n):
x = int(input("Enter a number"))
L.append(x)

f=0
x = int(input("Enter element to be searched "))

for i in range(n):
if L[i]== x:
f=1
if f==0:
print("Element does not exits")
else:
print("Element exists")

def highest():
L = []
n = int(input("Enter how many elements you want in the list"))
for i in range(n):
x = int(input("Enter a number"))
L.append(x)
max = L[0]
for i in L:
if i>max:
max = i
print("Greatest number of the list",L," is ",max)
def Exchange():
A = [2, 4, 1, 6, 7, 9, 23, 10,55,77]
N = len(A)
print ("The initial List is:", A)
if N%2==0:
for i in range(int(N/2)): # int(N/2): converting float to int
Tmp = A[i]
A[i] = A[(int(N/2)) + i]
21
A[int(N/2) + i] = Tmp
print ("The exchanged List is", A)
else:
print("N should be Even No")

def selection():
L = [5,1,5,11,4,9,6,13,2]
n = len(L)
for i in range(n):
min1 = L[i]
pos = i
for j in range (i+1,n):
if L[j] < min1:
min1 = L[j]
pos = j

t=L[i]
L[i]=L[pos]
L[pos]=t
print(L)

ch='y'
while ch == 'y' or ch=='Y':
print("---------------------")
print("List Operation Menu")
print("---------------------")
print("1. Linear search")
print("2. Find highest element in a list")
print("3. Exchange first half with second half of a list")
print("4. Sort List using selection sort")
x = int(input("Enter choice = "))
if x == 1:
search()
if x == 2:
highest()
if x == 3:
Exchange()
if x == 4:
selection()

ch = input("\nDo you want to continue Y/N = ")

22
OUTPUT

23
Program 12: Program to show various logical operation on nested List

def col_sum():
L = []
M=int(input("How many rows in a list"))
N = int(input("How many columns in a list"))
print("Enter elements :")
for i in range(M):
Row = []
for j in range(N):
x = int(input())
Row.append(x)
L.append(Row)
for i in range(M):
for j in range(N):
print(L[i][j],end=" ")
print()
s=0
s1=0
for i in range(N):
s=0
for j in range(M):
s = s + L[j][i]
print("Sum of " ,i," Column is ",s)

def diagnol_sum():
L = []
M=int(input("How many rows in a list"))
N = int(input("How many columns in a list"))
print("Enter elements :")
for i in range(M):
Row = []
for j in range(N):
x = int(input())
Row.append(x)
L.append(Row)
for i in range(M):
for j in range(N):
print(L[i][j],end=" ")
print()
s=0
s1=0
24
for i in range(M):
for j in range(N):
if i==j:
s =s + L[i][j]
if i== (N -j- 1):
s1 = s1 + L[i][j]
print("Sum of first diagonal " ,s)
print("Sum of second diagonal " ,s1)

def Transpose():
A = [[2,3,1,5,0],[7,1,5,3,1],[2,5,7,8,1],[0,1,5,0,1],[3,4,9,1,5]]
B = [[ 0 for x in range(5)]for x in range(5)]
print ("The original array is")
for i in range(5):
for j in range(5):
print ((A[i][j]),end=" ")
print()

for i in range(len(A)):
for j in range(len(A)):
B[j][i] = A[i][j]
print ("The Transpose is : ")
for i in range(len(A)):
for j in range(len(A)):
print ((B[i][j]), end=" ")
print()
ch='y'
while ch == 'y' or ch=='Y':
print("1. To find the sum of column element ")
print("2. To find the sum of diagnal elements")
print("3. To find transpose of a matrix")

x = int(input("Enter choice = "))


if x == 1:
col_sum()
if x == 2:
diagnol_sum()

if x == 3:
Transpose()

ch = input("\nDo you want to continue Y/N = ")


25
OUTPUT

26
Program 13: Program to implement all user defined functions of Dictionary

ch='y'
Stud = {'Name':'Arun','Class':12}
while ch == 'y' or ch=='Y':
print("1. creating a dictionary")
print("2. Updating dictionary")
print("3. Printing Dictinary keys")
print("4. Printing Dictonary values")
print("5. Printing Dictionary items")
print("6. Printing the value of given key")
print("7. Find Dictionary length")
print("8. Printing key and value using loop")
print("9. Printing key and value using loop and items() function")
print("10.Check in and not in membership operator")
print("11.Update dictionary")
print("12.Use del function")
print("13.Use pop function")
print("14.Use popitem() function")
print("15.Use clear function")
print("16.copy dictionary")
print("17.Sort keys")
print("18.Use fromkeys function")
x = int(input("Enter choice = "))
if x == 1:
ch1 = 'y'
while ch1=='y':
key = input("Enter a key -> ")
val = input("Enter a value of key -> ")
Stud[key] = val
print(Stud)
ch1 = input("Do You want to continue Y/N ")
if x == 2:
ch1 = 'y'
while ch1=='y':
key = input("Enter a key -> ")
val = input("Enter a value of key -> ")
Stud.update({key:val})
print(Stud)
ch1 = input("Do You want to continue Y/N ")
if x == 3:
print("Dictinary keys ",Stud.keys())
27
if x == 4:
print("Dictinary keys ",Stud.values())
if x == 5:
print("Dictinary keys ",Stud.items())
if x == 6:
key = input("Enter key whose value required ")
print(Stud[key])
print(Stud.get(key))
if x == 7:
print("Lenth of Dictionary ",len(Stud))
if x == 8:
for key in Stud:
print(key, " value is ", Stud[key])
if x == 9:
for key, value in Stud.items():
print({key},":",{value})
for key in Stud.keys():
print(key)
for value in Stud.values():
print(value)
if x == 10:
print('Name' in Stud)
print('Address' not in Stud)
print('Fees' in Stud)
if x == 11:
val = input("Enter a new name -> ")
Stud['Name'] = val
print(Stud)
Stud.update({'Name':'Rahul'})
print(Stud)
if x == 12:
print("1. To delete a particular element from list")
print("2. To delete complete list")
y = int(input("Enter the choice"))
if y == 1:
key = input("Enter a key to be deleted -> ")
del Stud[key]
print(Stud)
if y == 2:
del Stud
print(Stud) #this will cause an error because "Stud" no longer exists.
if x == 13:
28
key = input("Enter a key to be popped -> ")
Stud.pop(key)
print(Stud)
if x == 14:
Stud.popitem()
print(Stud)
if x == 15:
Stud.clear()
print(Stud)
if x == 16:
print("Stud ", Stud)
Stud1 = Stud
print("Stud1 = ",Stud1)
Stud1['Name'] = 'Rohan'
print("Stud after change in Stud1 ",Stud)
Stud2 = Stud.copy()
Stud2['Name'] = 'Romi'
print("stud after change is Stud2 ",Stud)
Stud3 = dict(Stud)
Stud3['Name'] = 'Vimal'
print("Stud after change in Stud 3 ",Stud)
if x == 17:
print(sorted(Stud))
if x == 18:
x = ('key1', 'key2', 'key3')
y = 0,1,2
thisdict = dict.fromkeys(x, y) #value if optional default value is none
print(thisdict)
ch = input("\nDo you want to continue Y/N = ")

29
OUTPUT

30
Program 14: Program to create and read text file.

ch = 'y'
while ch=='y' or ch == 'Y':
print("1. To create file ")
print("2. To read file ")
print("3. To create a file by replacing space with # character")
print("4. To display newly created file")
x = int(input("enter choice"))
if x == 1:
file1 = open("MyFile.txt","w")
L = ["I like pyhon\n","like SQL\n","and Networking\n"]
file1.writelines(L)
file1.close()
if x == 2:
file1 = open("MyFile.txt","r")
St = file1.read()
print(St)
file1.close()
if x == 3 :
file1 = open("MyFile.txt","r")
file2 = open("temp.txt","w")

St = file1.read()
for i in St:
if i ==' ':
file2.write('#')
else:
file2.write(i)

file1.close()
file2.close()

if x == 4:
file1 = open("temp.txt","r")
St = file1.read()
print(St)
file1.close()

ch = input("Do You want to continue Y/N ")

31
OUTPUT

32
Program 15: Write a program to read content of file line by line and display each word separated by '#'.

f = open("file1.txt","r")
for line in f:
words = line.split()
for w in words:
print(w+'#',end='')
print()
f.close()

NOTE : The original content of file is:


India is my country
I ove python
Python learning is fun

OUTPUT

33
Program 16: Write a program to read content of fileand display total number of vowels, consonants,
lowercase and uppercase characters.

f = open("file1.txt","r")
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:",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@

34
OUTPUT

35
Program 17: Write a program to create a binary file to store Rollno andname Search for Rollno and display
record if found otherwise "Roll no. notfound".

import pickle
student=[]
f=open('student.dat','wb')
while True:
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
student.append([roll,name])
ch=input("Add More ?(Y/N)")
if ch in "Nn":
break
pickle.dump(student,f)
f.close()
f=open('student.dat','rb')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
while True:
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 found==False:
print("Sorry! Roll number not found ")
ch=input("Search more ?(Y) :")
if ch in "Nn":
break
f.close()

36
OUTPUT

37
Program 18: Program to create binary file to store Rollno,Name and Marks and update marks of entered
Rollno.

import pickle
student=[]
f=open('student.dat','wb')
while True:
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ch=input("Add More ?(Y/N)")
if ch in "Nn":
break

pickle.dump(student,f)
f.close()
f=open('student.dat','rb+')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break

while True:
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 found==False:
print("Sorry! Roll number not found ")
ch=input("Update more ?(Y/N) :")
if ch in "Nn":
break
f.close()

38
OUTPUT

39
Program:19 Program to implement all operation on binary file.

import pickle
def write():
f=open("studentdetails.dat","wb")
record=[]
while True:
rno=int(input("Roll no:"))
name=input("Name:")
marks=int(input("Marks:"))
data=[rno,name,marks]
record.append(data)
ch=input("Do u want to enter more records(y/n)")
if ch in 'Nn':
break
pickle.dump(record,f)
print("Record added..")
f.close()

def read():
print("Contents in file ..")
f=open("studentdetails.dat","rb")
try:
while True:
s=pickle.load(f)

for i in s:
print(i)
except Exception:
f.close()

def append():
f=open("studentdetails.dat","rb+")
print("append data in file:")
rec=pickle.load(f)
while True:
rno=int(input("Roll no:"))
name=input("Name:")
marks=int(input("Marks:"))
data=[rno,name,marks]
rec.append(data)
ch=input("Do u want to enter more records(y/n)")
if ch in 'Nn':
break
f.seek(0)
pickle.dump(rec,f)
print("Record added..")
f.close()
40
def search():
f=open("studentdetails.dat","rb")
r=int(input("Enter roll no whose detail u want to search:"))
found=0
try:
while True:
s=pickle.load(f)
for i in s:
if i[0]==r:
print(i)
found=1
break
except Exception:
f.close()
if found==0:
print("Sory..record.. not found..")

def update():
f=open("studentdetails.dat","rb+")

r=int(input("Enter roll no whose detail u want to update:"))


f.seek(0)
try:
while True:
rpos=f.tell()
print(rpos)
s=pickle.load(f)
for i in s:
if i[0]==r:
i[1]=input("new name:")
i[2]=int(input("new marks:"))
f.seek(rpos)
pickle.dump(s,f)
break
except Exception:
f.close()

def delete():
f=open("studentdetails.dat","rb")
s=pickle.load(f)
f.close()

r=int(input("Enter roll no whose detail u want to delete:"))


f=open("studentdetails.dat","wb")
41
reclst=[]
for i in s:
if i[0]==r:
continue
reclst.append(i)
pickle.dump(reclst,f)
f.close()

def mainmenu():
print("----------------------------------------------")
print("1. Write data into the file..")
print("2. Read data from the file..")
print("3. Append data into the file..")
print("4. Search data from file..")
print("5. Update data in file..")
print("6. Delete from file..")
print("7. Exit..")
print("----------------------------------------------")
while True:
mainmenu()
ch=int(input("Enter your choice(1-7)"))
if ch==1:
write()
elif ch==2:
read()
elif ch==3:
append()
elif ch==4:
search()
elif ch==5:
update()
elif ch==6:
delete()
elif ch==7:
break

42
OUTPUT

43
Program 20: Program to write records of student in CSV file.

import csv
f=open("student.csv","w")
sw=csv.writer(f)
sw.writerow(["rollno","name","marks"])
rec=[]
while True:
r=int(input("Enter roll number:"))
n=input("Enter name:")
m=eval(input("Enter marks:"))
data=[r,n,m]
rec.append(data)
ch=input("do u want to enter more records?")
if ch=="n":
break
for i in rec:
sw.writerow(i)
f.close()

OUTPUT

44
Program 21: Program to read data from csv file student.csv

import csv
def read():
f=open("student.csv","r")
sreader=csv.reader(f)
for i in sreader:
print(i)

read()

OUTPUT

45
Program 22: Program to write in a csv file using writerow() function and new delimiter ';'.

import csv
f=open("student.csv","w",newline="")
sw=csv.writer(f,delimiter=";")
sw.writerow(["rollno","name","marks"])
rec=[]
while True:
print("enter student record:")
r=int(input("enter roll number:"))
n=input("enter name:")
m=int(input("enter marks"))
sr=[r,n,m]
rec.append(sr)
ch=input("do you want to enter more records y/n")
if ch=="n":
break
for i in rec:
sw.writerow(i)
f.close()

OUTPUT

46
Program 23: Program to read data from csv file student.csv

import csv
def read():
f=open("student.csv","r")
sreader=csv.reader(f)
for i in sreader:
print(i)

read()

OUTPUT

47
Program 24: write a program to connect with database and display records of emp table.

import mysql.connector
con=mysql.connector.connect(host="localhost",
user="root",
password="123456",
database="employee")
cur=con.cursor()
cur.execute("select * from emp")
rec=cur.fetchone()
while rec:
print("name=",rec[0],"eno=",rec[1],"dob=",rec[2],"salary=",rec[3])
rec=cur.fetchone()

con.commit()
print("query executed successfully")

OUTPUT

48
Section-B ( MYSQL )

Q1.Write an SQL Query to create database employee.

mysql> create database employee;


Query OK, 1 row affected(0.15 sec)

mysql> show databases;


+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| employee |
| school |
| test |
| xif |
| xiic |
| xiic21 |
| xiif ||
+--------------------+
9 rows in set (0.00 sec)

Q2. Write an SQL Query to open database employee.

mysql> use employee;


Database changed
mysql>

Q3. Write an SQL Query to create table empl.

49
Q4.Write an SQL Query to show the structure of the table.

Q5. Write an SQL Query to Insert 7 records.

Q6.Write an SQL Query to display all records from table empl.

50
Q7. Write an SQL Query to display EmpNo and Ename of all employees from the table empl.

Q8.Write an SQL Query to display Employees who earn more than 40000.

Q9.Write an SQL Query to display Employees who work as Accountant.

51
Q10.Write an SQL Query to add a column Commission to Table Empl.

Q11.Write an SQL Query to Increase the Salary of all employees by 10% in the table Empl.

Q12.Write an SQL Query to set commission as 5% of salary of Sales Executive.

Q13.Write SQL query to display Ename, Salary, and Salary added with comm. from table empl.

52
Q14.Write an SQL Query to display the details of employees whose name have only five letters.

Q15.Write an SQL Query to display Empno, Ename, Salary, and Sal*12 as Annual Salary.

Q16.Write an SQL Query to display the name of employee whose name contains “r” as third letter.

53
Q17. Write an SQL Query to display the name and salary of those employees whose salary is between
35000 and 40000.

Q18. Write an SQL Query to change Ename ‘Sam’ by ‘Samuel’.

54
Q19.Write an SQL Query to display tables data according to descending order of salary.

Q20.Display job wise total salary of employees using GROUP BY clause.

Q21.Write an SQL Query to delete entire table IF EXISTING.

55
Program 1:-
Program to connect with database and store record of employee and display records.

import mysql.connector as mycon


con = mycon.connect(host="localhost",user="root",password="123456",charset="utf8")
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("3. 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()
for i in result:
print(i)

elif choice==3:
con.close()
print("## Bye!! ##")

else:
print("## INVALID CHOICE ##")

56
OUTPUT:

1. ADD RECORD
2. DISPLAY RECORD
3. EXIT
Enter Choice :1
Enter Employee Number :101
Enter Name:Ankit
Enter Department :Sales
Enter Salary :50000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
3. EXIT
Enter Choice :1
Enter Employee Number :102
Enter Name:Yash
Enter Department :Purchase
Enter Salary :45000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
3. EXIT
Enter Choice :2
(101, 'Ankit', 'Sales', 50000)
(102, 'Yash', 'Purchase', 45000)
1. ADD RECORD
2. DISPLAY RECORD
3. EXIT
Enter Choice :3
## Bye!! ##
>>>

57
Program 2: Program to connect with database and update the employee record of
entered empno.

import mysql.connector as mycon


con = mycon.connect(host="Localhost",user="root",password="123456",database="company",charset="utf8")
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:
for i in result:
print(i)
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,(PRESS ENTER, IF NOT WANT TO CHANGE )")
s = int(input("ENTER NEW SALARY,(PRESS ENTER, IF NOT WANT TO CHANGE ) "))
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 / N) :")

58
OUTPUT:

########################################
EMPLOYEE UPDATION FORM
########################################

ENTER EMPNO TO UPDATE :101


(101, 'Ankit', 'Sales', 50000)

## ARE YOUR SURE TO UPDATE ? (Y) :y


== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==
ENTER NEW DEPARTMENT,(PRESS ENTER, IF NOT WANT TO CHANGE )Marketing
ENTER NEW SALARY,(PRESS ENTER, IF NOT WANT TO CHANGE ) 60000
## RECORD UPDATED ##
UPDATE MORE (Y/N) :n

59
Program 3:Program to connect with database and search employee number in table
employee and display record, if empno not found display appropriate message.

mysql.connector as mycon
con = mycon.connect(host="Localhost",user="root",password="123456",database="company",charset="utf8")
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:
for i in result:
print(i)

ans=input("SEARCH MORE (Y / N) :")

60
OUTPUT:

########################################
EMPLOYEE SEARCHING FORM
########################################

ENTER EMPNO TO SEARCH :1010


Sorry! Empno not found
SEARCH MORE (Y) :y
ENTER EMPNO TO SEARCH :101
(101, 'Ankit', '', 70000)
SEARCH MORE (Y / N) :n
>>>

61
Program 4:Program to connect with database and delete the employee record of entered
empno.

import mysql.connector as mycon


con = mycon.connect(host="Localhost",user="root",password="123456",database="company",charset="utf8")
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:
for row in result:
print(row)
choice=input("\n## ARE YOU 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 / N) :")

62
OUTPUT:

########################################
EMPLOYEE DELETION FORM
########################################

ENTER EMPNO TO DELETE :101


(101, 'Ankit', '', 70000)

## ARE YOUR SURE TO DELETE ? (Y) :y


=== RECORD DELETED SUCCESSFULLY! ===
DELETE MORE ? (Y / N) :n
>>>

*********************************

63

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy