You are on page 1of 47

1

2
Exp.NO:1 Date:
Aim:Create Table Garment and Fabric -Python -Sql Connectivity. Insert Records, delete
record of an with fcode. Modify the price of any fcode

Source code:

msql=con=cur=''

def connection():

global msql, con, cur

import mysql.connector as msql

con=msql.connect(host='localhost',user='root',

passwd='student')

if con.is_connected():

cur=con.cursor()

cur.execute('use comp_sci')
Abhishek R
else: 2

print("no connection")

def crt_tables():

global msql, con,cur

connection()

try:

cur.execute(' Create database comp_sci')

3
except:

print("Database already exist")

try:

cur.execute('use comp_sci')

gmt_qry='create table Garment\

(GCODE int(5) primary key,\

Description varchar(17),\

PRICE int(5),\

FCODE varchar(3),\

READYDATE date)'

fab_qry='create table Fabric\

(FCODE char(3) primary key,\

TYPE varchar(15))'

cur.execute(gmt_qry)

cur.execute(fab_qry)

except:

print("Table Garment and Fabric Exist...\n")

def inst_garment():

4
global msql, con,cur

print("Insert Records in Table Garments...")

try:

while True:

gcd=input("Enter GCode: ")

dscpn=input("Enter Description: ")

pc=input("Enter Price: ")

fcd=input("Enter FCode: ")

rdt=input("Enter ReadyDate: ")

qry='insert into garment values({},"{}",{},"{}","{}")'

cur.execute(qry.format(gcd,dscpn,pc,fcd,rdt))

con.commit()

ch=input("Add more records [y/n]:")

if ch.lower()!='y':

break

except:

print("Error in garment table")

def view_grmnt():

5
global msql, con,cur

cur.execute("select * form garment")

rs=cur.fetchall()

print(70*'=')

print('{:<15}{:<15}{:<15}{:<15}{:<15}'

.format('GCode','Description','Price','FCode','ReadyDate')

print(70*'=')

for row in rs:

for col in range(len(row)):

print('%-15s'%row[col],end='')

print()

print(70*'=')

print("Number of Records=",cur.rowcount)

def inst_fabric():

global msql, con,cur

6
print("Insert Records in Table Fabric..")

try:

while True:

gcd=input("Enter FCode: ")

tp=input("Enter Type:" )

qry='insert into fabric values("{}","{})'

cur.execute(qry.format(gcd,tp))

con.commit()

ch=input("Add more Records [y/n]:")

if ch.lower()!='y':

break

except:

print("Error in Fabric table")

def view_fabric():

global msql, con,cur

cur.execute("select * form fabric")

rs=cur.fetchall()

print(' '*5,20*'=')

7
print('%12s%12s'%('FCODE','TYPE'))

print(' '*5,20*'=')

for row in rs:

for col in range(len(row)):

print('{:<12}'.format(row[col]),end='')

print()

print(' '*5,20*'=')

print(' '*5,"Number of Records=",cur.rowcount)

def modify_grmnt():

gcd=input("Enter GCode to modify price: ")

qry="Select * from garments where gcode={}"

cur.execute(qry.format(gcd))

rs=cur.fetchall()

if rs:

pce=input("Enter New Price1: ")

qry='update garment set price={} where gcode={}'

cur.execute(qry.format(gcd))

8
con.commit()

print("\nSuccessfully updated...")

else:

print("\nRecord not found...")

def del_grmnt():

gcd=input("Enter GCode to be deleted: ")

qry="Select * from garment where gcode={}"

cur.execute(qry.format(gcd))

rs=cur.fetchall()

is rs:

qry='delete from garment where gcode={}'

cur.execute(qry.format(gcd))

con.commit()

print("\nRecord Not Found...")

else:

print("\nRecord not Found...")

connection()

msg="\n\

9
1. Create Tables\n\

2. View Garments and Fabric\n\

3. Insert in Garment\n\

4. Insert in Fabric\n\

5. Modify price In Garment\n\

6. Delet a record in Garment\n\

7. Exit"

while True:

print(msg)

ch=int(input("Input your choice"))

if ch==1:

crt_tables()

elifch==3:

inst_garment()

elifch==4:

inst_fabric()

elifch==2:

view_grmnt()

view_fabric()

10
elifch==5:

modify_grmnt()

elifch==6:

def_grmnt()

elifch==7:

break

else:

print("invalid Choice...")

con.close()

Output:

1.Create Tables

2. View Garments and Fabric

3. Insert in Garment

4. Insert in Fabric

5. Modify Price in Garment

6. Delete a Record in Garment

7. Exit

Input Your Choice: 2

11
=========================================================================

GCode Description Price FCodeReadyDate

=========================================================================

10001 Formal Shirt 1250F012008-01-12

10007 Formal Pant 1350F012008-03-09

10009 Informal Pant 1500F022008-10-20

10012 Informal Shirt 1550F021008-06-06

10015 Wedding Gown 5000F032009-09-15

10019 Evening Gown 850 F03 2008-06-06

10020Frock750 F04 2007-09-09

10023 Pencil Skirt 1150 F03 2008-12-19

10024 Baby Top 750 F032007-04-07

10025 Saree 3500 F032009-09-15

10026 Parallels 2300 F012008-02-17

10089 SLACKS 750 F032008-10-31

10090 Tulip Skirt 850 F022007-03-31

=========================================================================

Number of records = 13

12
==========================

FCODE TYPE

==========================

F01Terelene

F02 Cotton

F03 Silk

F04Polyster

F05 Jute

F06 Net

===========================

Number of records= 6

Input your Choice: 5

Enter GCode to modify price: 10020

Enter New Price: 750

Successfully Updated…

Input Your Choice: 6

Enter GCode to be deleted: 10015

Successfully Deleted…

13
Exp NO: 2 Date:

Aim
Write a program in python for Sql connectivity Consider tables emp and dept tables:
(a) Add a column HRA with default value 2000
(b) Modify HRA for the employee whose empno is input by the user.
(c) Display name, job and annual salary of employees whose comm is assigned in descending
order of salary.
(d) Delete the record of employee whose employee number input by the user
(e) Display empno, name, job and department name who are either a manger or a clerk
(f) Display minimum and maximum, sum and average of salary along with number of
records in each job.

Source Code

import mysql.connector

from tabulate import tabulate

clm_bool = False

try:

mydb = mysql.connector.connect(host="localhost",user =
'root',password="student",database = 'abhith')

mycurs = mydb.cursor()

except:

print("Connection error")

14
def del_rec():

if mydb.is_connected() :

try:

empno = input("Enter the Employee Number to be deleted")

mycurs.execute(f'DELETE FROM emp WHERE empno = {empno}')

mydb.commit()

print('Record Sucessfully Deleted\n')

except:

print('Record Not Present in Table..../Error in command')

else:

print("Database Connection Error,Run again\n")

def disp_agg():

if mydb.is_connected() :

15
mycurs.execute('select job,count(*),min(sal),max(sal),sum(sal),avg(sal) from emp group
by job')

rows = mycurs.fetchall()

if rows:

print(tabulate(rows,headers =
('job','count(*)','min(sal)','max(sal)','sum(sal)','avg(sal)'),tablefmt="grid"))

else:

print("Empty Table, Insert Records")

else:

print("Database Connection Error,Run again\n")

def disp_comm():

if mydb.is_connected() :

mycurs.execute('select empname, job,sal from emp where comm is not NUll order by
saldesc')

rows = mycurs.fetchall()

if rows:

print(tabulate(rows,headers = ('empname','job','sal'),tablefmt="grid"))

else:

print("Empty Table, Insert Records")

16
else:

print("Database Connection Error,Run again\n")

def disp_mc():

if mydb.is_connected() :

mycurs.execute('select e.empno,e.empname,e.job,d.dname from emp e natural join dept


d where job in ("Manager","Clerk");')

rows = mycurs.fetchall()

if rows:

print(tabulate(rows,headers = ('empno','empname','job','dname'),tablefmt="grid"))

else:

print("Empty Table, Insert Records")

else:

print("Database Connection Error,Run again\n")

def add_clm():

global clm_bool

17
clm_bool = True

if mydb.is_connected():

try:

mycurs.execute(f'alter table EMP\

ADD COLUMN HRA INT DEFAULT 2000')

except:

print("Column Already Exists")

else:

print("Database Connection Error,Run again\n")

def mod_rec():

if mydb.is_connected():

empno = input('Enter EMP of Employee whose details are to be modified: ')

hra= int(input("Enter the new house allowance: "))

mycurs.execute(f'update emp set hra = {hra} where empno = {empno}')

mydb.commit()

else:

print("Database Connection Error,Run again\n")

18
def disp_table():

if mydb.is_connected() :

mycurs.execute('select * from emp')

rows = mycurs.fetchall()

if rows and clm_bool==True:

print(tabulate(rows,headers =
('empno','empname','job','mgr','hiredate','sal','comm','deptno','hra'),tablefmt="grid"))

elif rows and clm_bool == False:

print(tabulate(rows,headers =
('empno','empname','job','mgr','hiredate','sal','comm','deptno'),tablefmt="grid"))

else:

print("Empty Table, Insert Records")

else:

print("Database Connection Error,Run again\n")

19
#crt_table()

print("Welcome to the Program: ")

print('++++++++++++++++++++++++++++++++++++++++++++++')

while True:

choice = int(input('\n\

1) Add Column HRA\n\

2) Display name, job and annual salary of employees whose comm is assigned in
descending order of salary\n\

3) Display minimum and maximum, sum and average of salary along with number of
records in each job.\n\

4) Display empno, name, job and department name who are either a manger or a
clerk.\n\

5) Modify House Allowance\n\

6) Delete a record\n\

7) View Table\n\

8) Exit:'))

if choice==1:

add_clm()

if choice==2:

20
disp_comm()

if choice==3:

disp_agg()

if choice==4:

disp_mc()

if choice==5:

mod_rec()

if choice==6:

del_rec()

if choice==7:

disp_table()

if choice==8:

print("THANK YOU FOR USING THE PROGRAM")

mydb.close()

break

21
Output

22
23
24
25
Exp NO:3 Date:

Aim: Write a python menu driven program to implement a stack[LIFO] using a list data
structure.

Souce Code:

s=[]

c="y"

while(c=="y"):

print("1. PUSH")

print("2. POP")

print("3. DISPLAY")

choice=int(input("Enter Your Choice: "))

if choice==1:

a=input("Enter a number: ")

s.append(a)

elif choice==2:

if (s==[]):

print("Stack Empty")

else:

print("Delted Element is: ",s.pop())

elif choice==3:

26
l=len(s)

for i in range(l-1,-1,-1):

print(s[i])

else:

print("Wrong Input")

c=input("DO you want to Continue?")

Ouput:

1. PUSH

2. POP

3. DISPLAY

Enter Your Choice: 1

Enter a number: 5

DO you want to Continue?y

1. PUSH

2. POP

3. DISPLAY

Enter Your Choice: 1

Enter a number: t

DO you want to Continue?y

27
1. PUSH

2. POP

3. DISPLAY

Enter Your Choice: 1

Enter a number: 66

DO you want to Continue?y

1. PUSH

2. POP

3. DISPLAY

Enter Your Choice: 3

66

DO you want to Continue?y

1. PUSH

2. POP

3. DISPLAY

Enter Your Choice: 2

Delted Element is: 66

28
DO you want to Continue?y

1. PUSH

2. POP

3. DISPLAY

Enter Your Choice: 3

DO you want to Continue?n

29
MYSQL

Exp.NO:4Date:

Aim: Consider tables garment and Fabric.

a) Display min, max, sum and average price for each fabric codes in table Garments.

b) Find the total number of garments of each Type.

c) Increase the price of ‘SLACKS’ by 150.

30
d) Display Fabric Code, description, price and all types of Garments

e) Display Maximum Fabric code, minimum Ready date.

f) Display different fabric codes.

g) Display number of different garment codes.

31
h) Display number of different fabric codes.

i) Display the name of fabrics whose length contains less than 7 characters.

j) Display the name of fabrics ready in 2008( using function year and LIKE -2commands)

32
k) Display Equi-join.

l) Display Natural join.

33
Exp. NO:5Date:

Aim:Create a student table with student id, name and marks in 5 subjects
(Eng, Phy, Che, Maths, CS)

a) Add coloumns TOT and Grade

b) Update TOT and Grade using queries.

34
c) Delete the details of a student in the above table whose mark is not assigned.

d) Display the details of students with marks more than 80.

e) Display the min,max,sum and average of the marks.

f) Order the(Student ID, Name and marks) table in descending order of the marks.

35
g) Add the record-‘s104’,’Catherine’,95,76,NULL,74,63.

h) Change CHE=80 and GRADE=’A’ for the student with id s104.

36
Exp No:6 Date:

Aim: Consider Tables EMP and Dept.

a) Display number of employees, sum and average sal in each department from
tables Emp and Dept.

37
b) Display, Empname, Deptno and dname from tables Emp and Dept.

c) Display number of Employees, sum and average sal in each job.

d) Display number of employees, sum and average sal in each job where number of
employees less than 2.

38
e) Display name of senior most Employee.

f) Display minimum salary and last hiring date.

g) Display average commission in the table Employee.

Exp NO:7 Date:

39
Consider Tables : Flights and Fares.

Write commands to display;


1) Fl_No and No_Flights from Kanpur to Bangalore.

2) Arrange the contents of flights in descending order of Fl_No.

40
3) Display Fl_No, Airlines and Fare to be paid for the flights from Delhi to
Mumbai from tables flights and Fares where Fare to be paid=Fare+ Fare*
Tax/100

4) Minimum fare Indian Airlines offering from table Fares.

Write output of the flowing:

41
1) SELECT A.Fl_No, No_Flights FROM Flights A, Fares B
WHERE Starting=’Delhi’ AND A.Fl_No=B.Fl_No;

2) SELECT COUNT(DISTINCT Ending) FROM Flights;

EXP NO:8 date:

42
Consider Table: Furniture

Write commands to display:


1. Information about the baby cots.

2. Item name which are priced more than 15000.

3. Item name and type in which date of stock is before 22-01-2002 in decreasing
order of item name.

43
4. Item name and date of stock of those items in which discount percentage is more
than 25.

5. Count number of items whose type is ‘sofa’.

6. Insert a row: 14, Velvet Touch, Double Bed ,25-03-2003,25000,30

44
Write output of the following:

7. SELECT COUNT(DISTINCT Type)FROM FURNITURE;

8. SELECT MAX(Discount) FROM Furniture;

9. SELECT AVG(DISCOUNT) FROM Furniture WHERE Type=’Baby Cot’;

45
10. SELECT SUM(Price) FROM Furniture WHERE DateofStock<’2002-02-12’;

46

You might also like