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

Practical File (Xii - Ip) 2023-24

PRACTICAL FILE management

Uploaded by

naliso4962
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)
47 views

Practical File (Xii - Ip) 2023-24

PRACTICAL FILE management

Uploaded by

naliso4962
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/ 40

NO.

4 JAIPUR

SESSION : 2023-24

CLASS - XII

INFORMATICS PRACTICES
(PYTHON / MYSQL)
INDEX
Sl. Date Program Page No. Grade/ Sign. Of
No. (From - To) Remarks Teacher
1 Calculating the cube of the series
elements.
2 Series – cube calculation and display
of result based on condition.
3 Updation in Series data
4 Display of attributes of Series
5 Add and display of data in/from
dataframe
6 Creation of dataframe by list of
dictionaries and display of its attributes.
7 Performing arithmetic operations on
dataframe
8 Display of top 2 and bottom 2 achivers
from dataframe
9 Accessing data from dataframe
10 Add, update, remove data from
datafram Covid_df
11 Creation of line chart
12 Plotting Bar chart
13 Plotting of a graph for the function
y = 𝒙𝟐
14 Creation of multiple line charts on
common plot
15 Creation of an array in the range 1 to 20
with values 1.25 apart. Another array
containing the log values of the
elements stored in first array.
Then plotting of different graphs.
16 Creation of histogram
17 Fetching data from mysql table EMP for
a Job type entered by user
18 Fetching data from mysql table EMP
and group by a particular column
19 Shop application to search mobile in
database by brand or Price range.
20 Database operation to add , modify,
update, display records from emp table.
21 SQL queries – 20 Nos.
LAB ACTIVITY 1
Write a program in python to calculate the cube of the series values as
given below-
2,5,7,4,9

Code :

import pandas as pd #Importing pandas module

S_data = pd.Series([2,5,7,4,9]) #Creation of Series

#Printing of Original Series data


print("Original Series data")
print(S_data)

#Calculation and Printing of cubes of all data from new Series


print("Cube of Series data")
Cube_data= S_data**3
print(Cube_data)

OUTPUT
Original Series data
0 2
1 5
2 7
3 4
4 9
dtype: int64
Cube of Series data
0 8
1 125
2 343
3 64
4 729
dtype: int64
LAB ACTIVITY 2

Write a program in python to create a series Ser1 of numeric data with labels as
a,b,c,d,e. Then create a new series object Ser2, contains squares of each values
from Ser1. Display Ser2 values which are greater than 15.

Code :

import pandas as pd #Importing pandas module

Ser1 = pd.Series([2,3,5,4,1], index=['a','b','c','d','e']) #Creation of Series Ser1

#Printing of Original Series data


print("Series Ser1 data")
print(Ser1)

Ser2= Ser1**2 #Calculation the square of Ser1 and stored in Ser1


print(Ser2[Ser2>15]) #Checking the values which are greater than 15 and printing

OUTPUT

Series Ser1 data


a 2
b 3
c 5
d 4
e 1
dtype: int64
c 25
d 16
dtype: int64
LAB ACTIVITY 3
Write a program in python to update the following series by writing code for question
(i) to (v)
Kiran 33
Manvendra 48
Saswati NaN
Yash 43
(i) Add a new student Dev with marks 40
(ii) Fill all missing values by 0.
(iii) Update marks of Manvendra and Saswati by 44.
(iv) Display all information of Yash and Manvendra. (First display Yash then Manvendra)

PROGRAM

import pandas as pd
import numpy as np

# Creation of Series object Ser


data = [33, 48, np.NaN, 43]
Ser = pd.Series(data, index=['Kiran','Manvendra', 'Saswati', 'Yash'])
print(Ser) OUTPUT

# Adding a new student Dev with marks 40


Ser['Dev']=40 Kiran 33.0
print(Ser) Manvendra 48.0
Saswati NaN
# filling of missing values as 0 Yash 43.0
Ser.fillna(0, inplace=True) dtype: float64
print(Ser) Kiran 33.0
Manvendra 48.0
# Updation of marks for Manvendra and Saswati by 44 Saswati NaN
Ser[1:3]=44 Yash 43.0
print(Ser) Dev 40.0
dtype: float64
# Dispaly of marks for Yash and Manvendra Kiran 33.0
print(Ser[['Yash','Manvendra']]) Manvendra 48.0
# Other ways to access this data Saswati 0.0
# Ser[[3,1]] Yash 43.0
# Ser[-2:-5:-2] Dev 40.0
dtype: float64
Kiran 33.0
Hint : Numeric index, Index labels, Back indexing Manvendra 44.0
Saswati 44.0
0 1 2 3 4 Yash 43.0
Kiran Manv Sas Yash Dev Dev 40.0
-5 -4 -3 -2 -1 dtype: float64
Yash 43.0
Manvendra 44.0
dtype: float64
LAB ACTIVITY 4
Write a program in python to create two series objects Obj1 and Obj2 (data given below) and
display the following attributes in the format given below.
Structure of Series objects Output format
Obj1 Obj2 Attribute Name Object 1 Object 2
A 6700 A 640 Data Type
B 5600 B 720 Shape
C 5000 C 1020 No. of Bytes
D 5200 D 437 No. of Dimensions
Item Size
E nil
Has Nans?
Empty
PROGRAM
import pandas as pd
import numpy as np

Obj1 = pd.Series([6700,5600,5000,5200,np.NaN], index=['A', 'B', 'C', 'D', 'E'])


Obj2 = pd.Series([640,720,1020,437], index=['A', 'B', 'C', 'D'])

print("Attribute Name\t\tObject 1\t\tObject 2")


print("_______________________________________________________")
print("Data Type\t\t", Obj1.dtype, "\t\t", Obj2.dtype)
print("Shape \t\t", Obj1.shape, "\t\t\t", Obj2.shape)
print("No. of Bytes\t\t", Obj1.nbytes, "\t\t\t", Obj2.nbytes)
print("No. of Dimensions\t",Obj1.ndim,"\t\t\t",Obj2.ndim)
print("Item Size \t",Obj1.size,"\t\t\t",Obj2.size)
print("Has Nans? \t\t",Obj1.hasnans,"\t\t\t",Obj2.hasnans)
print("Empty \t",Obj1.empty,"\t\t\t",Obj2.empty)
OUTPUT

Attribute Name Object1 Object 2


_________________________________________
Data Type float64 int64
Shape (5,) (4,)
No. of bytes 40 32
No. of Dimensions 1 1
Item Size 5 4
Has Nans? True False
Empty False False
LAB ACTIVITY 5
Write a program in python to create a dataframe fruits from following data and answer the
questions (i) to (v)-
Color Count Price
Orange Yellow 30 40
Orange Green 19 30
Mango Yellow 25 60
Mango Green 29 120
Pear Green 65 150
(i) Add a new column ‘Variety’ contains data as ‘Normal’, ‘Normal’, ‘Dashari’, ‘Hafooj’, ‘Normal’
(ii) Add a new row ‘Apple’ containing Red,40,190,Kashmiri.
(iii) Display price of all fruits.
(iv) Display color and price of all fruits.
(v) Display count to variety all columns.

PROGRAM
import pandas as pd OUTPUT
import numpy as np
Color Count Price
Orange
Yellow 30 40
dict = {'Color':['Yellow','Green','Yellow','Green','Green'], OrangeGreen 19 30
'Count':[30,19,25,29,65], MangoYellow 25 60
'Price':[40,30,60,120,150]} Mango Green 29 120
Pear Green 65 150
fruits=pd.DataFrame(dict, index=['Orange','Orange','Mango','Mango','Pear'])
Color Count Price Variety
print(fruits) Orange Yellow 30 40 Normal
Orange Green 19 30 Normal
Mango Yellow 25 60 Dashari
#Adding a new column Variety
Mango Green 29 120 Hafooj
fruits['Variety']=['Normal', 'Normal', 'Dashari', 'Hafooj', 'Normal'] Pear Green 65 150 Normal
print(fruits) Color Count Price Variety
Orange Yellow 30 40 Normal
Orange Green 19 30 Normal
#Adding a new row Apple Mango Yellow 25 60 Dashari
fruits.loc['Apple']=['Red',40,190,'Kashmiri'] Mango Green 29 120 Hafooj
print(fruits) Pear Green 65 150 Normal
Apple Red 40 190 Kashmiri
Orange 40
#Display price of all fruits Orange 30
print(fruits['Price']) Mango 60
Mango 120
Pear 150
#Display color and price of all fruits Apple 190
print(fruits[['Color','Price']]) Name: Price, dtype: int64
Color Price
Orange Yellow 40
#Display count to variety all columns Orange Green 30
print(fruits.loc[:,'Count':'Variety']) #fruits.iloc[ : , 1:4]) Mango Yellow 60
Mango Green 120
Pear Green 150
Apple Red 190
Count Price Variety
Orange 30 40 Normal
Orange 19 30 Normal
Mango 25 60 Dashari
Mango 29 120 Hafooj
Pear 65 150 Normal
Apple 40 190 Kashmiri
LAB ACTIVITY 6
Consider the following data and write python code for points (i) to (v)
Color Count Price
Orange Yellow 30 40
Orange Green 19 30
Mango Yellow 25 60
Mango Green 29 120
Pear Green 65 150
(i) Write code to create a dataframe fruits using list of dictionaries.
(ii) Write code to display following attributes of dataframe-
Index, Columns, axes, datatype, no. of elements, dimensions, data in numpy, check
empty dataframe, no. of axes, transpose
PROGRAM

import pandas as pd
import numpy as np

dict = [ {'Color': 'Yellow', 'Count':30, 'Price':40},


{'Color': 'Green', 'Count':19, 'Price':30},
{'Color': 'Yellow', 'Count':25, 'Price':60},
{'Color': 'Green', 'Count':29, 'Price':120},
{'Color': 'Green', 'Count':65, 'Price':150} ]

fruits=pd.DataFrame(dict, index=['Orange','Orange','Mango','Mango','Pear'])
print(fruits)

#Displaying different attributes of dataframe fruits

print("Index Labels :",fruits.index)


print("Column Labels :",fruits.columns)
print("Axes :",fruits.axes)
print("Data type :",fruits.dtypes)
print("Total items in all columns :",fruits.size)
print("No. of Rows and Columns :",fruits.shape)
print("Data :\n",fruits.values)
print("Check if empty :",fruits.empty)
print("No. of axes :",fruits.ndim)
print("Transpose :\n",fruits.T)
OUTPUT
LAB ACTIVITY 7

Write a program in python to perform following arithmetic operations on dataframe.


df1 df2
3 4 5 2 8 3
2 7 nan nan 5 5
3 2 1 nan nan 2

PROGRAM

import pandas as pd
import numpy as np
#Creation of dataframe df1
df1 = pd.DataFrame([[3,4,5],[2,7,np.NaN],[3,2,1]])
print("df1\n",df1)
#Creation of dataframe df2
df2 = pd.DataFrame([[2,8,3],[np.NaN,5,5],[np.NaN,np.NaN,2]])
print("df2\n",df2)

#Addition of two dataframe


df3=df1+df2 # df3 = df1.add(df2)
print("df1+df2\n",df3)

# Subtraction of df2 from df1


df4=df1-df2 # df4 = df1.sub(df2) , df4 = df2.rsub(df1)
print("df1 - df2\n",df4)

#Multiplication of two dataframe


df5=df1*df2 #df5 = df1.mul(df2)
print("df1 X df2\n",df5)

#Division operation in two dataframe


df6=df1/df2 # df6 = df1.div(df2) , df6 = df2.rdiv(df1)
print("df1/df2\n",df6)

#Scaler arithmetic’s
df7=df1 + 10
print("df1 + 10\n",df7)
OUTPUT

df1
0 1 2
0 3 4 5.0
1 2 7 NaN
2 3 2 1.0
df2
0 1 2
0 2.0 8.0 3
1 NaN 5.0 5
2 NaN NaN 2

df1+df2
0 1 2
0 5.0 12.0 8.0
1 NaN 12.0 NaN
2 NaN NaN 3.0

df1 - df2
0 1 2
0 1.0 -4.0 2.0
1 NaN 2.0 NaN
2 NaN NaN -1.0

df1 X df2
0 1 2
0 6.0 32.0 15.0
1 NaN 35.0 NaN
2 NaN NaN 2.0

df1/df2
0 1 2
0 1.5 0.5 1.666667
1 NaN 1.4 NaN
2 NaN NaN 0.500000

df1 + 10
0 1 2
0 13 14 15.0
1 12 17 NaN
2 13 12 11.0
LAB ACTIVITY 8
Consider the following data frame of classes –
Class Name Subject gradeA Year
1 I Vinita EVS 24 2020
2 II Harish English 26 2020
3 III Amit Maths 20 2020
4 IV Deepak Hindi 21 2020
5 V Anil GK 29 2020

Write code to display the details of teacher(s), having highest number of gradeA students and lowest
number of gradeA students. (2 from top and 2 from bottom)
PROGRAM
import pandas as pd
# Creation of dictionary for given data
dict = {'Class':['I','II','III','IV','V'],
'Name':['Vinita','Harish','Amit','Deepak','Anil'],
'Subject':['EVS','English','Maths','Hindi','GK'],
'gradeA':[24,26,20,21,29],
'Year':[2020,2020,2020,2020,2020]}

#Creation of DataFrame
DfRecord = pd.DataFrame(dict, index=[1,2,3,4,5])
print("Original Dataframe")
print(DfRecord)

#Sorting of dataframe’s data in respect of column ‘gradeA’ in descending order


SortedData=DfRecord.sort_values ( by = ['gradeA'], ascending=False)
print("Sorted Dataframe in ascending order")
print(SortedData)

#Display of top two teachers


print("Top 2 teachers, having highest number of students got A grades ")
Top2 = SortedData.head(2)
print(Top2)

#Display of bottom two teachers


print("Bottom 2 teachers, having lowest number of students got A grades ")
Bottom2 = SortedData.tail(2)
print(Bottom2)
OUTPUT
LAB ACTIVITY 9
Write a program to create a the following dataframe and answer the questions (i) to (xv)-
Datafrme name : Covid_df

Masks Gloves Amount


SMS 30000 80000 2700000
AIIMS 50000 1500000 4200000
SDMH 10000 500000 200000
FORTIS 15000 5000 150000
SDMH 35000 30000 2500000
(i) Display number of masks bought by SMS.
(ii) Display amount paid by all hospitals.
(iii) Display amount paid by AIIMS and SMS in same sequence.
(iv) Display masks bought by Fortis
(v) Display all details of Fortis hospital.
(vi) Display total gloves bought by AIIMS using index only.
(vii) Find all rows with label ‘SDMH’ with all columns.
(viii) Find hospital paid amount more than 200000.
(ix) List single True or False to signify if all amount more than 200000 or not.
(x) List 2nd , 3rd and 4th rows.
(xi) List only the columns Masks and Amount.
(xii) List columns 0 to 1 .
(xiii) List only rows with labels AIIMS and FORTIS
(xiv) List only rows 0,2,3
(xv) Display data of rows AIIMS, SDMH and columns Masks and Gloves

PROGRAM
import pandas as pd

dict = {'Masks': [30000,50000,10000,15000,35000],


'Gloves':[80000,1500000,500000,5000,30000],
'Amount':[2700000,4200000,20000,150000,2500000]}

Covid_df = pd.DataFrame(dict, index=['SMS','AIIMS','SDMH','FORTIS','SDMH'])


print(Covid_df)

#(i) Display number of masks bought by SMS.


print("\nMasks bought by SMS = ",Covid_df.Masks['SMS'])

#(ii)Display amount paid by all hospitals.


print("\nAmount paid by all hospitals\n", Covid_df['Amount'])

#(iii) Display amount paid by AIIMS and SMS in same sequence.


print("\nAmount paid by SMS and AIIMS\n", Covid_df.loc[['AIIMS','SMS'],['Amount']])
#(iv) Display masks bought by Fortis
print("\nMasks bought by Fortis Hospital = ", Covid_df['Masks']['FORTIS'])

#(v) Display all details of Fortis hospital.


print("\nFortis Hospital =\n ", Covid_df.loc['FORTIS'])

#(vi) Display total gloves bought by AIIMS using index only.


print("\n",Covid_df.iloc[1:2,1:2]) # Covid_df.iloc[1,1]

#(vii) Find all rows with label ‘SDMH’ with all columns.
print("\n",Covid_df.loc['SDMH',:]) # Covid_df.loc['SDMH']

#(viii) Find hospital paid amount more than 200000.


print("\n",Covid_df[Covid_df['Amount']>200000])

#(ix) List single True or False to signify if all amount more than 200000 or not.
print("\nChecking if all row contains amount greater than 200000 =
",(Covid_df['Amount']>200000).all())

#(x) List 2nd , 3rd and 4th rows.


print("\n",Covid_df.iloc[1:4,:])

#(xi) List only the columns Masks and Amount.


print("\n",Covid_df[['Masks','Amount']])

#(xii) List columns 0 to 1.


print("\n",Covid_df.iloc[:, 0:2])

#(xiii) List only rows with labels AIIMS and FORTIS


print("\n",Covid_df.loc[['AIIMS','FORTIS']])

#(xiv) List only rows 0,2,3


print("\n",Covid_df.iloc[[0,2,3]])

#(xv) Display details of Masks and Gloves bought by AIIMS and SDMH
print("\n",Covid_df.loc[['AIIMS','SDMH'],['Masks','Gloves']])
OUTPUT
LAB ACTIVITY 10
Write a program to create a the following dataframe and answer the questions (i) to (v)-
Datafrme name : Covid_df

Masks Gloves Amount


SMS 30000 80000 2700000
AIIMS 50000 1500000 4200000
SDMH 10000 500000 200000
FORTIS 15000 5000 150000
SDMH 35000 30000 2500000
(i) Add new row as
SHALBY 5000 20000 150000
(ii) Add a column as Remarks with data -> Paid, Pending,Paid, Paid,Pending, Paid
(iii) Remove rows labelled as SMS and FORTIS.
(iv) Update remarks of AIIMS as Paid.
(v) Remove columns Amount and Remarks.

PROGRAM

‘‘‘(i) Add new row as


SHALBY 5000 20000 150000’’’
Covid_df.loc['SHALBY'] = [5000,20000,150000]
print(Covid_df)

#(ii) Add a column as Remarks with data-->Paid, Pending,Paid, Paid,Pending,Paid


Covid_df['Remarks'] = ['Paid','Pending','Paid','Paid','Pending','Paid']
print(Covid_df)

#(iii) Remove rows with label SMS and FORTIS.


Covid_df.drop(['SMS','FORTIS'], inplace=True)
print(Covid_df)

#(iv) Update remarks of AIIMS as Paid.


Covid_df.loc['AIIMS','Remarks']='Paid' #Covid_df.at['AIIMS','Remarks']='Paid'
print(Covid_df)

#(v) Remove columns Amount and Remarks.


Covid_df.drop(['Amount','Remarks'],axis=1, inplace=True)
print(Covid_df)
OUTPUT
LAB ACTIVITY 11

Write a program to create a line chart for following data-


x=[2,4,3,7,5]
y=[23,43,18,20,5]
Write code to
(a) Display dashed line
(b) Display + (plus) marker
(c )Change the marker color to blue

PROGRAM
#Importing modules for matplotlib.pyplot
import matplotlib.pyplot as plt
x=[2,4,3,7,5]
y=[23,43,18,20,5]
plt.plot(x,y,color='r',linestyle='dashed',marker='+',markeredgecolor='b')
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

OUTPUT
LAB ACTIVITY 12

Write a program to plot a bar chart in python to display the result of a school for five
consecutive years.
(a) Change the colour bars in sequence as red,yellow,green,blue,cyan
(b) Change width of bars in sequence as 0.5,0.6,0.7,0.8,0.9

PROGRAM
#Importing modules for matplotlib.pyplot
import matplotlib.pyplot as plt
Years=[2014,2015,2016,2017,2018]
PerResult=[91.0,89.7,84.2,98.9,94.3]
clr=['r','y','g','b','c']
wd=[0.5,0.6,0.7,0.8,0.9]
plt.bar(Years,PerResult,color=clr,width=wd)
plt.xlabel("Years")
plt.ylabel("Result in percentage")
plt.show()

OUTPUT
LAB ACTIVITY 13

Write a program in python to plot a graph for the function y = 𝒙𝟐

PROGRAM
import matplotlib.pyplot as plt
x_cords = range(-50,50)
y_cords = [x*x for x in x_cords]

plt.plot(x_cords, y_cords)
plt.show()

OUTPUT
LAB ACTIVITY 14
Write a program to create multiple line charts on common plot where three data ranges are
plotted on the same chart.
The data ranges to be plotted are-
DATA = [[5.,42.,28.,18.],[9.,13.,22.,29.],[8.,32.,26.,40.]]
(i) Display legends as Range1,Range2 and Range3.
(ii) Display label on x and y axes as X and Y respectively.
(iii) Add title as “Multirange line chart”

PROGRAM
import numpy as np
import matplotlib.pyplot as plt
DATA = [[5.,42.,28.,18.],[9.,13.,22.,29.],[8.,32.,26.,40.]]
x=np.arange(4)
plt.plot(x,DATA[0],color='b',label='Range1')
plt.plot(x,DATA[1],color='y',label='Range2')
plt.plot(x,DATA[2],color='g',label='Range3')
plt.legend(loc='upper left')
plt.title("Multirange line chart")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

OUTPUT
LAB ACTIVITY 15
Write a program to create an array in the range 1 to 20 with values 1.25 apart.

Another array containing the log values of the elements stored in first array.
(a) Create a plot of first vs second array; specify the x-axis (containing first array's values) title as
'Random Values' and y-axis title as 'Logarithm Values'
(b) Create a third array that stores the COS values of first array and then plot both the second and
third arrays vs first array. The COS values should be plotted with a dashdotted line.
(c) Change the marker type as a circle with the blue color in second array.
(d) Create a scatter chart as this : second array data points as blue small diamonds, third array data
points as black circle.

PROGRAM
import numpy as np
import matplotlib.pyplot as plt
a=np.arange(1,20,1.25)
b=np.log(a)

"""(a) Create a plot of first vs second array; specify the x-axis (containing first array's values) title as
'Random Values' and y-axis title as 'Logarithm Values'"""
plt.plot(a,b)
plt.xlabel('Random Values')
plt.ylabel('Logarithm values')
plt.show()

"""(b) Create a third array that stores the COS values of first array and then plot both the second and
third arrays vs first array. The COS values should be plotted with a dashdotted line."""
c=np.cos(a)
plt.plot(a,b)
plt.plot(a,c,linestyle='dashdot')
plt.show()

"""(c) Change the marker type as a circle with the blue color in second array."""
c=np.cos(a)
plt.plot(a,b)
plt.plot(a,c,'bo',linestyle='dashdot')
plt.show()
"""(d) Create a scatter chart as this : second array data points as blue small diamonds, third array data
points as black circle."""
c=np.cos(a)
plt.plot(a,b,'bd')
plt.plot(a,c,'ro')
plt.show()

OUTPUT
LAB ACTIVITY 16
Write a program to create the histogram for (a) to (g). The data is given below-
Weight measurements for 16 small orders of French Fries (in grams).
78 72 69 81 63 67 65 73
79 74 71 83 71 79 80 69
(a) Create a simple histogram from above data.
(b) Create a horizontal histogram from above data.
(c) Create a step type of histogram from above data.
(d) Create a cumulative histogram from above data.

PROGRAM
import numpy as np
import matplotlib.pyplot as plt
wff=np.array([78,72,69,81,63,67,65,75,79,74,71,83,71,79,80,69]) #weight of French fries

"""(a) Create a simple histogram from above data."""


plt.hist(wff)
plt.show()

"""(b) Create a horizontal histogram from above data."""


plt.hist(wff, orientation='horizontal')
plt.show()

"""(c) Create a step type of histogram from above data."""


plt.hist(wff,histtype='step')
plt.show()

"""(d) Create a cumulative histogram from above data."""


plt.hist(wff,cumulative=True)
plt.show()
OUTPUT
LAB ACTIVITY 17
Write a program in python to fetch and display records of perticular JOB entered by user from
mysql table emp stored in database test (given in emp.csv file in C: drive)

PROGRAM

import mysql.connector as msc


import pandas as pd

try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "test")
crs = mydb.cursor()

#Fetching data of employees for perticular JOB type entered by user


jobtype=input("Write the name of JOB from CLERK,SALESMAN,MANAGER,ANALYST,PRESIDENT
to display list of employees working= ")
print("Records of employees working as ",jobtype)
qry="select * from emp where Job like %s"
crs.execute(qry,(jobtype,))
data1 =crs.fetchall()
df = pd.DataFrame(data1,
columns=["Ecode","Ename","Sex","Job","MGR","Hiredate","Sal","Comm","Dname"])
print(df)
crs.close()
except mysql.connector.Error as error:
print("Records not available")
ex=input("press any key to exit")

OUTPUT
LAB ACTIVITY 18
Write a program in python to count number of emloyees group by a perticular column entered
by user from mysql table emp stored in database test (given in emp.csv file in C: drive)

PROGRAM
import mysql.connector as msc
import pandas as pd

try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "test")
crs = mydb.cursor()

#Fetching data of employees for perticular JOB type entered by user


qry="select * from emp"
crs.execute(qry)
data1 =crs.fetchall()
df = pd.DataFrame(data1,
columns=["Empno","Ename","Sex","Job","MGR","Hiredate","Sal","Comm","Dname"])
print(df)
k=1
while(k == 1):
colum=input("Write the name of column to group the records= ")
print("Total employees ",colum," wise is given below-")
Agg_data=df.groupby([colum]).count()
#Peforming dataframe operation
print(Agg_data["Ename"])
crs.close()
k=int(input("To group again,enter '1' or press other key to close"))
except mysql.connector.Error as error:
print("Records not available")
ex=input("press any key to exit")
OUTPUT
LAB ACTIVITY 19
Write a program in python to display the details of mobiles a per he range of price entered by
user from mysql table mobile stored in database store (given in mobile.csv file in C: drive)
Use command in mysql to load file :
load data local infile 'c:\\mobile.csv' into table mobile fields terminated by ',' lines terminated by
'\r\n';

PROGRAM
import os
import mysql.connector as msc
import pandas as pd

try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "store")
crs = mydb.cursor()

k=1
while(k==1):
print("***************************************************************")
print("*******************MOBILE DATA MANAGEMENT**********************")
print("***************************************************************")
print("\nSEARCH MOBILE by\n1. By Brand Name\n2.By Price Limit\n3.Exit")
choice=int(input("Enter your choice = "))
if(choice==1):
os.system('cls')
brand=input("Enter Brand Name to search = ")
qry="select * from mobile where Mname= %s"
crs.execute(qry,(brand,))
data1 =crs.fetchall()
df = pd.DataFrame(data1, columns=["Mcode","Mname","Features","Year_manuf","Price"])
print(df)
elif(choice==2):
os.system('cls')
print("To Check by Price limits ")
min_price=input("Enter the Minimum price limit to buy =")
max_price=input("Enter the Maximum price limit to buy =")
qry="Select * from mobile where Price>= %s and Price<= %s"
crs.execute(qry,(min_price,max_price,))
data1 =crs.fetchall()
df = pd.DataFrame(data1, columns=["Mcode","Mname","Features","Year_manuf","Price"])
print(df)
elif(choice==3):
exit()
else:
os.system("ls")
print("Enter correct choice")
k=int(input("Press 1 to continue, press other key to exit "))
except mysql.connector.Error as error:
print("Database Error")

OUTPUT
LAB ACTIVITY 20
Write a program in python to perform the following operations on mysql table emp stored in
database test -
(a) Display data of all employee.
(b) Add new employee data in table emplyee.
(c) Update data of employee based on empployee ID entered by user.
(d) Remove the records of employee based on their employee ID entered by user.
(e) Exit the program.

PROGRAM

import mysql.connector as msc


import pandas as pd

def display():
try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "office")
crs = mydb.cursor()
print("Employees Data")
crs.execute("SELECT * FROM emp")
data1 =crs.fetchall()
df = pd.DataFrame(data1, columns=["Ecode","Ename","Designation","Salary"])
print(df)
crs.close()
except mysql.connector.Error as error:
print("Records not available")

def insert():
try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "office")
crs = mydb.cursor()
print("Inserting in new data")
ecode=int(input("Enter a new employee code="))
ename=input("Enter a name of employee=")
desig=input("Enter designation=")
salary=int(input("Enter salary="))
qry="INSERT INTO emp VALUES(%s,%s,%s,%s)"
data=(ecode,ename,desig,salary)
crs.execute(qry,data)
mydb.commit()
print(crs.rowcount,"Records Inserted")
crs.close()
except mysql.connector.Error as error:
print("Failed to insert record in table emp")

def delete():
try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "office")
crs = mydb.cursor()
nm=input("Enter name of employee to delete=")
qry="DELETE FROM emp WHERE ename LIKE %s"
crs.execute(qry,(nm,))
mydb.commit()
crs.close()
except mysql.connector.Error as error:
print("Failed to delete record from table emp")

def update():
try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "office")
crs = mydb.cursor()
code=int(input("Enter employee code to update data="))
nm=input("Enter new name=")
desig=input("Enter new designation=")
sal=int(input("Enter salary="))
qry="UPDATE emp SET ename=%s, designation=%s, salary=%s Where ecode=%s"
data=(nm,desig,sal,code)
crs.execute(qry,data)
mydb.commit()
crs.close()
except mysql.connector.Error as error:
print("Failed to update records in table emp")

k=0
while(k!=5):
print("*************MENU**************")
print("1. Insert new record")
print("2. Delete records")
print("3. Update records")
print("4. Display all records")
print("5. Exit")
k=int(input("Enter your choice="))
if(k==1):
insert()
elif(k==2):
delete()
elif(k==3):
update()
elif(k==4):
display()
else:
exit

OUTPUT
MYSQL
Write Queries for the followings:-
1. Write a query to display all contents of table employee table.
Ans.
SELECT *
FROM emp;
--------------------------------------------------------------------------------------------------------------------------------
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ---------- --------- ---------- --------- ---------- ---------- ---------- -------------------------------------------------
7369 SMITH CLERK 7902 17-DEC-1980 800 NULL 20
7499 ALLEN SALESMAN 7698 20-FEB-1981 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30
7566 JONES MANAGER 7839 02-APR-1981 2975 NULL 20
7654 MARTIN SALESMAN 7698 28-SEP-1981 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-1981 2850 NULL 30
7782 CLARK MANAGER 7839 09-JUN-1981 2450 NULL 10
7788 SCOTT ANALYST 7566 19-APR-1987 3000 NULL 20
7839 KING PRESIDENT 17-NOV-1981 5000 NULL 10
7844 TURNER SALESMAN 7698 08-SEP-1981 1500 700 30
7876 ADAMS CLERK 7788 23-MAY-1987 1100 NULL 20
7900 JAMES CLERK 7698 03-DEC-1981 950 NULL 30
7902 FORD ANALYST 7566 03-DEC-1981 3000 NULL 20
7934 MILLER CLERK 7782 23-JAN-1982 1300 NULL 10
---------------------------------------------------------------------------------------------------------------------------------
2. Write a query to display different jobs from employee table.
Ans.
SELECT distinct(job)
FROM emp;

JOB
---------
ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN

3. Write a query to display the empname who is earning more than 2500.
Ans.
SELECT ename
FROM emp
WHERE sal>2500;

ENAME
----------
JONES
BLAKE
SCOTT
KING
FORD
4. Write a query to display the managers working in department number 10.
Ans.
SELECT ename
FROM emp
WHERE JOB=”MANAGER” and deptno=10;

ENAME
---------
CLARK

5. Write a query to display the name of employee joined on or after 01-MAY-1981.


Ans.
SELECT ename
FROM emp
WHERE hiredate>='01-MAY-1981';

ENAME
----------
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER

6. Write a query to display the managers who earn more than 2800.
Ans.
SELECT ename,job
FROM emp
WHERE job='MANAGER' AND sal>2800;

ENAME JOB
---------- ---------
JONES MANAGER
BLAKE MANAGER

7. Write a query to display the department number where more than three employees are
working.
Ans.
SELECT deptno
FROM emp
GROUP BY deptno
HAVING count(*)>3;

DEPTNO
--------
20
30
8. Write a query to display the name of employee with their salary in order of their joining.
Ans.
SELECT ename,sal
FROM emp
ORDER BY hiredate;

ENAME SAL
---------- ----------
SMITH 800
ALLEN 1600
WARD 1250
JONES 2975
BLAKE 2850
CLARK 2450
TURNER 1500
MARTIN 1250
KING 5000
JAMES 950
FORD 3000
MILLER 1300
SCOTT 3000
ADAMS 1100

9. Write a query to display the name and salary from department number 30 and sorted in
descending order of salary.
Ans.
SELECT ename,sal
FROM emp
WHERE deptno=30
ORDER BY sal DESC;

ENAME SAL
---------- ----------
BLAKE 2850
ALLEN 1600
TURNER 1500
MARTIN 1250
WARD 1250
JAMES 950

10. Write a query to display maximum salary paid in each deptno.


Ans.

SELECT deptno,max(sal)
FROM emp
GROUP BY deptno;

DEPTNO MAX(SAL)
------ ----------
10 5000
20 3000
30 2850
11. Write a SQL command to increase the salary by 300 to the employees belong to deptno 20.
Ans.
UPDATE emp
SET sal=sal+300
WHERE deptno=20;
5 rows updated.

12. Write a query to display number of employee in each department.


Ans.
SELECT deptno, count(*) as noofemp
FROM emp
GROUP BY deptno;

DEPTNO NOOFEMP
------ ----------
10 3
20 5
30 6

13. Insert the following data in table employee-


8000,'DEVESH','CLERK',7200,'01-JAN-2011',3500,0,10

Ans.
INSERT INTO emp
VALUES (8000,'DEVESH','CLERK',7200,'01-JAN-2011',3500,0,10);

14. Write a query to display the employee name earning between 1500 and 2500.
Ans.
Method-1
SELECT ename
FROM emp
WHERE sal>=1500 AND sal<=2500;

Method-2
SELECT ename
FROM emp
WHERE sal BETWEEN (1500 and 2500);

ENAME
---------
ALLEN
CLARK
TURNER

15. Write a query to display the employee name joined in the year 1981.
Method-1
SELECT ename
FROM emp
WHERE hiredate>='01-JAN-1981' AND hiredate<='31-DEC-1981';
Method-2
SELECT ename
FROM emp
WHERE hiredate between ("01-JAN-1981" and "31-DEC-1981");

Method-3
SELECT ename
FROM emp
WHERE year(hiredate)="1981";

ENAME
--------
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
KING
TURNER
JAMES
FORD

16. Write a query to display details of employees working in any department out of 10 and 20.
Method-1
SELECT *
FROM emp
WHERE deptno =10 OR deptno=20;

Method-2

SELECT *
FROM emp
WHERE deptno IN (10,20);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ---------- --------- ---------- ---------- ---------- -------------------------------------------------
7369 SMITH CLERK 7902 17-DEC-1980 800 20
7566 JONES MANAGER 7839 02-APR-1981 2975 20
7782 CLARK MANAGER 7839 09-JUN-1981 2450 10
7788 SCOTT ANALYST 7566 19-APR-1987 3000 20
7839 KING PRESIDENT 17-NOV-1981 5000 10
7876 ADAMS CLERK 7788 23-MAY-1987 1100 20
7902 FORD ANALYST 7566 03-DEC-1981 3000 20
7934 MILLER CLERK 7782 23-JAN-1982 1300 10
17. Write a query to display details of employees getting some commission.

SELECT *
FROM emp
WHERE comm IS NOT NULL;
--------------------------------------------------------------------------------------------------------------------------------
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ---------- --------- ---------- --------- ---------- ---------- ---------- -------------------------------------------------
7499 ALLEN SALESMAN 7698 20-FEB-1981 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-1981 1250 1400 30
7844 TURNER SALESMAN 7698 08-SEP-1981 1500 700 30
--------------------------------------------------------------------------------------------------------------------------------

18. Write a query to see average salary paid to department number 20.
SELECT AVG(sal)
FROM emp
WHERE depno=20;

AVG(sal)
------------
2175

19. Write a query to delete the records of employees working as analyst and working in department number
20.

DELETE FROM emp


WHERE Job = “ANALYST” AND deptno=20;

02records deleted

20. Write a query to create the following table –


Table – Customer

Name of Field Datatype Size Contraints


Cno Integer 5 Primary Key
Cname Varchar 30 Not Null
Gender Char 1
DOB Date >= “2003-01-01”
Amountpaid Float 10,2 Default “Free”
Remarks Varchar 100

CREATE TABLE Customer


(
Cno INT(5) Primary Key,
Cname VARCHAR(30) NOT NULL,
Gender CHAR(1)
DOB DATE CHECK DOB >= “2003-01-01”,
Amountpaid FLOAT(10,2) DEFAULT “Free”,
Remarks VARCHAR(100)
)

You might also like