You are on page 1of 29

-------------------------------------------------------- 1-------------------------------------------------------

1.Write a Python program with the function empinfo() to store the employee
details [eid, ename, sal, designation] into the binary file and display the records
which are having salary above 50000 using the function empdetails().

PROGRAM

import pickle

def empinfo():

f=open('employee.dat','wb')

q=[]

n=int(input('enter the no of employee records :'))

for i in range(n):

e=int(input('enter the employee id : '))

m=input('enter the employee name : ')

s=int(input('enter the employee salary : '))

d=input('enter the employee designation : ')

print('\n')

q.append([e,m,s,d])

pickle.dump(q,f)

f.close()

def empdetails():

f=open('employee.dat','rb')

while True:
try:

d=pickle.load(f)

except EOFError:

break

print('The employees with salary more than 50000')

for i in range(len(d)):

if d[i][2] > 50000:

print(d[i])

f.close()

empinfo()

empdetails()

-------------------------------------------------------------------------------------------------------------------
2.Check the given table

· Create the table with the above structure under the database
XYZ_Software_Developers
· Insert the respective records into the table
· Update the salary of the employees holding manager position by 5%
Add a new column location into the table and update the values to all columns.

· 1
create table dev(
-> dev_id int(11) not null primary key auto_increment ,
-> team_id int(11) not null ,
-> name varchar(100) unique ,
-> position varchar(100),
-> technology varchar(100),
-> salary int(11)
-> );

· 2
· 3
update dev set salary=salary*1.05 where position = 'designer';

· 4
· alter table dev add location varchar(50);
update dev set location = 'CHENNAI' where dev_id=1 ;
update dev set location = 'DELHI' where dev_id=2;

-------------------------------------------------------------------------------------------------------------------
3
Write a Python MySQL database connectivity program to perform the following
operation.
Create a database ABC_School
A table should be created with the name student_info with the following attributes
Sid – integer – primary key
Sname- string
Total – float
Fname – string
Mname – string
Dob – date
Doj – date
Mobile – string
Email – string.
Insert the data into the above table and update the table by adding a column fees
with decimal (7, 2) data type

import mysql.connector as mycon


con = mycon.connect(host='localhost', user='root', password="5074")
cur = con.cursor()
cur.execute("create database if not exists ABC_SCHOOL")
cur.execute("use ABC_SCHOOL")
cur.execute("create table if not exists student_info(sid int, sname varchar(20), total decimal(7,2), fname
varchar(50),mname varchar(50),dob date , doj date , mobile varchar(12),email varchar(50))")
con.commit()
s= int(input("Enter Student ID :"))
n = input("Enter Name : ")
t = float(input("Enter Total : "))
f=input("Enter Father Name : ")
m=input("Enter Mother Name : ")
d=input('enter date of birth : ' )
j=input('enter date of joining : ' )
i=input('enter mobile number : ')
e=input('enter email ID : ')

query="insert into student_info values({},'{}',{},'{}','{}','{}','{}','{}','{}')".format(s,n,t,f,m,d,j,i,e)


cur.execute(query)
con.commit()
print('\n\tdata saved')
q=alter table student_info add fees decimal(7,2)
cur.execute(q)
con.commit()

-------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------

2
1.Write a Python program with the function empinfo() to store the employee
details [eid, ename, sal, designation] into the CSV file and display the records
which are having salary above 50000 using the function empdetails().

import csv
def empinfo():
f=open('emp.csv','w',newline='\n')
w=csv.writer(f)
h=['eid', 'ename,' 'sal', 'designation']
w.writerow(h)
a='y'
while a.lower()=='y':
e=int(input('enter the employee id : '))
n=input('enter the employee name : ')
s=int(input('enter the employee salary : '))
d=input('enter the employee designation : ')
rec=[e,n,s,d]
w.writerow(rec)
a=input('enter y to continue :')
f.close()
print('\n\t Record Saved')
def empdetails():
f=open('emp.csv','r')
r=csv.reader(f)
result=next(r)
print('The Employees with salaries or more than 50000')
for i in r:
if int(i[2]) >=50000:
print(i)
f.close()
empinfo()
empdetails()
-------------------------------------------------------------------------------------------------------------------
2.Check the given table

·Create the table STUDENT_INFO with the above structure under the
database GSPS
· Insert the respective records into the table
· Update the marks of the student by 5 whose name ends with ‘raj’
Add a new column class into the table and update the values to all columns.

1.

mysql> create table student_info(


-> stud_id int not null primary key ,
-> stud_code varchar(15) ,
-> stud_name varchar(35),
-> subject varchar(25) ,
-> marks int,
-> phone varchar(15)
-> );

2.

3.
update student_info set marks=marks+5 where stud_name like '%Z';

alter table student_info add class varchar(15) ;


-------------------------------------------------------------------------------------------------------------------

3.Write a Python MySQL database connectivity program to perform the following


operation.
Create a database Product
A table should be created with the name product_info with the following
attributes
pid – integer – primary key
pname- string
price – float
Manufacturer_name – string
Manufacturer_Location – string
MFG_Date – date
Exp_Date – date
Mobile – string
Email – string.
Insert the data into the above table and update the table structure by adding a
column MRP with decimal (5, 2) data type.
Retrieve the details of the products which MRP is above 1000.

import mysql.connector as mycon


con = mycon.connect(host='localhost', user='root', password="5074")
cur = con.cursor()
cur.execute("create database if not exists product")
cur.execute("use product")
cur.execute("create table if not exists product_info(pid int, pname varchar(20), price decimal(7,2),
manufaturer_name varchar(50),manufaturer_location varchar(50),mfg_date date , exp_date date ,
mobile varchar(12),email varchar(50))")
con.commit()
s= int(input("Enter Product ID :"))
n = input("Enter Product Name : ")
t = float(input("Enter price : "))
f=input("Enter Manufaturer Name : ")
m=input("Enter Manufaturer location : ")
d=input('enter MFG date : ' )
j=input('enter EXP date : ' )
i=input('enter mobile number : ')
e=input('enter email ID : ')
print('\n\tdata saved')
q='alter table product_info add MRP decimal(7,2)'
cur.execute(q)
con.commit()
mrp=int(input('enter MRP :'))
query="insert into product_info values({},'{}',{},'{}','{}','{}','{}','{}','{}',{})".format(s,n,t,f,m,d,j,i,e,mrp)
cur.execute(query)
con.commit()
q1='select * from product_info'
cur.execute(q1)
res=cur.fetchall()
for i in res:
if int(i[9]) > 1000:
print('Product with Mrp greater than 1000')
print(i[0],'\t',i[1],'\t',i[2],'\t',i[3],'\t',i[4],'\t',i[5],'\t',i[6],'\t',i[7],'\t',i[8],'\t',i[9])
con.commit()
con.close()

-------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------

3.
1.Write a program to read a text file “Sample.txt” and count and display the
number of lines starting with ‘A’ or ‘I’ (Separate count is to be printed).

def count():
try:
with open('sample.txt', 'r') as f:
lines = f.readlines()

count_a = 0
count_i = 0

for line in lines:


if line.startswith('A'):
count_a += 1
elif line.startswith('I'):
count_i += 1

print(f"Number of lines starting with 'A': {count_a}")


print(f"Number of lines starting with 'I': {count_i}")

except:
print('\t{file not found}')

count()
file contents in sample.txt
Python is a high-level, general-purpose programming language.
Its design philosophy emphasizes code readability with the use of significant indentation
Python is dynamically typed and garbage-collected.
It supports multiple programming paradigms, including structured (particularly procedural), object-
oriented and functional programming.
It is often described as a "batteries included" language due to its comprehensive standard library
Guido van Rossum began working on Python in the late 1980s as a successor to the ABC programming
language and first released it in 1991 as Python 0.9.0.
Python 2.0 was released in 2000.
Python 3.0, released in 2008, was a major revision not completely backward-compatible with earlier
versions.
Python 2.7.18, released in 2020, was the last release of Python 2.
Python consistently ranks as one of the most popular programming languages, and has gained
widespread use in the machine learning community

-------------------------------------------------------------------------------------------------------------------

2 2 4
.Check the given table
· Create the table ExAM_INFO with the above structure under the
database GSPS
· Insert the respective records into the table
· Update the marks of the student by 5 whose attendance is above 180
days.
· Modify the column percentage to float data type
· Display the student details in descending order of marks.
II.
III.

-------------------------------------------------------------------------------------------------------------------

3.Write a Python MySQL database connectivity program to perform the following


operation.
Create a database Library
A table should be created with the name Library_info with the following attributes
bid – integer – primary key, name- string, price – float,
Publisher_name – string, Publisher _Location – string, Publish_Date – date
Mobile – string, Email – string.
Insert the data into the above table and update the table structure by adding a
column MRP with decimal (5, 2) data type.
Retrieve the details of the books which MRP is above 1000 & published by ’ TATA
McGraw Hill’.
import mysql.connector as mycon
con=mycon.connect(user="root",password="5074")
cur=con.cursor()
cur.execute("create database if not exists lib")
cur.execute("use lib ")
cur.execute("CREATE TABLE IF NOT EXISTS Library_info (bid INT PRIMARY KEY, name VARCHAR(255), price
FLOAT, Publisher_name VARCHAR(255), Publisher_Location VARCHAR(255), Publish_Date DATE, Mobile
VARCHAR(15), Email VARCHAR(255) )")
s= int(input("Enter book ID :"))
n = input("Enter book Name : ")
t = float(input("Enter price : "))
f=input("Enter publisher Name : ")
m=input("Enter publisher location : ")
d=input('enter publishing date : ' )
i=input('enter mobile number : ')
e=input('enter email ID : ')
cur.execute("ALTER TABLE Library_info ADD COLUMN MRP DECIMAL(10, 2)")
j=int(input('enter the mrp : '))
query="insert into library_info values({},'{}',{},'{}','{}','{}','{}','{}',{})".format(s,n,t,f,m,d,i,e,j)
cur.execute(query)
cur.execute("SELECT * FROM Library_info WHERE MRP > 1000 AND Publisher_name = 'TATA McGraw
Hill'")
books = cur.fetchall()
print("Books with MRP above 1000 and published by 'TATA McGraw Hill':")
for i in books:
print(i[0],'\t',i[1],'\t',i[2],'\t',i[3],'\t',i[4],'\t',i[5],'\t',i[6],'\t',i[7],'\t',i[8])
con.close()
-------------------------------------------------------------------------------------------------------------------

4
-------------------------------------------------------- --------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------

1.Create a binary file named student.dat with roll number, name and marks. Input
a roll number and update the marks. Perform the operation of writing data using
insert_ student() and update data using update_student() methoods respectively.

import pickle
def insert_student():
f=open('students.dat','wb')
q=[]
n=int(input('enter the no of students records :'))
for i in range(n):
e=int(input('enter the student roll no : '))
m=input('enter the student name : ')
s=int(input('enter the student marks : '))
print('\n')
q.append([e,m,s])
pickle.dump(q,f)
f.close()
def update_student():
f=open('students.dat','rb+')
while True:
try:
d=pickle.load(f)
except EOFError:
break
n=int(input('enter roll number to be updated : '))
for i in range(len(d)):
if d[i][0] == n:
m=input('enter the student name : ')
s=int(input('enter the student marks : '))
d[i][1]=m
d[i][2]=s
print('\n\t{Record Updated}')
print('\n\t{Records}')
for i in range(len(d)):
print(d[i])
f.close()
insert_student()
update_student()
2.Check the given table

·Create the table School_INFO with the above structure under the database
GSPS_School
· Insert the respective records into the table
· Update the table structure by removing the primary key.
· Add the new column School_Contact_no to the table.
Display all the details available in table.

I.
II.

III.

IV.
---------------------------------------------------------------------------------

3.Write a Python MySQL database connectivity program to perform


the following operation.
Create a database Bank
A table should be created with the name Customer_info with the
following attributes
cid – integer – primary key, cname- string, price – float,
acc_no – integer, branch _Location – string, Acc_open_Date – date
Mobile – string, Email – string, Type_of_Accoun – String, Bal –
decimal(10, 2)
Insert the data into the above table and update the table structure by
adding a column RD – decimal (6,2
Retrieve the details of the account holders who process account in
the branch – Sirkali and the user name begins with ‘V’. Display the
result sorted by descending order of the balance.

import mysql.connector as mycon


con = mycon.connect(host='localhost', user='root', password="5074")
cur = con.cursor()
cur.execute("create database if not exists Bank")
cur.execute("use Bank")

cur.execute("create table if not exists Customer_info(cid int not null primary key, cname
varchar(20), price float, acc_no int ,branch_location varchar(50),acc_open_date date , mobile
varchar(12),email varchar(50),acc_type varchar(50),Bal decimal(10, 2))")
con.commit()
s= int(input("Enter Customer ID :"))
n = input("Enter Customer Name : ")
t = float(input("Enter price : "))
f=int(input("Enter acc_no : "))
m=input("Enter branch_location: ")
d=input('enter Acc_open_Date : ' )
i=input('enter mobile number : ')
e=input('enter email ID : ')
j=input('enter the type of account : ')
p=float(input('enter the balance : '))
query="insert into Customer_info values({},'{}',{},'{}','{}','{}','{}','{}','{}',
{})".format(s,n,t,f,m,d,i,e,j,p)
cur.execute(query)
con.commit()
print('\n\tdata saved')
q='alter table Customer_info add RD decimal(15,2)'
cur.execute(q)
l=float(input('enter RD :'))
cur.execute('update Customer_info set RD = {}'.format(l))
con.commit()
q2='select * from Customer_info where branch_location = "sirkali" and cname like "v%"'
cur.execute(q2)
res=cur.fetchall()
for i in res:
print(i[0],'\t',i[1],'\t',i[2],'\t',i[3],'\t',i[4],'\t',i[5],'\t',i[6],'\t',i[7],'\t',i[8],'\t',i[9],'\t',i[10])
con.close()
---------------------------------------------------------------------------------
---------------------------------------------------------------------------------
---------------------------------------------------------------------------------
5.

1.PushBook(Book) to add a new book entry as book_no and


book_title in the list of Books , considering it to act as push
operations of the Stack data structure. PopBook(Book) function
returns the value deleted from the stack. DisplayBook(Book) to
display book details.

def pushbook():
books=[]
a='y'
while a.lower()=='y':
bno = int(input('enter the book number : '))
bt = input('enter the book title : ')
print('\n')
rec=[bno , bt ]
books.append(rec)
a=input('to add more { "y" } : ')
return books
def popbooks(b):
if len(b)==0:
l=int(input('Stack is empty , if want to add books {y} :'))
if l.lower() == 'y':
pushbook()
else:
print('popped element {',b.pop(),'}')
print('\n')
def dispbooks(b):
print('\t{displaying books list}')
for i in b:
print('\t',b)
a=pushbook()
popbooks(a)
dispbooks(a)

---------------------------------------------------------------------------------
2.Check the given table
·Create the tables with mentioned names
·Insert the respective records into the table
·Update the table structure byadding bid as primary key for table product
and foreign key for table brand.
· Display the average rating of Medimix and Dove brands
Display the name, price, and rating of products in descending order of rating.

I.
II.
---------------------------------------------------------------------------------
3.Write a Python MySQL database connectivity program to perform the following
operation.
Create a database Train
A table should be created with the name Passenger_info with the following
attributes
pid – integer – primary key, Pname- string, pnr_no – int, source – string,
destination – string, train_name – string, train-no – integer, arrival_time – time,
journey_date – date, distance – float, ticket_price – float
Insert the data into the above table and update the table structure by adding a
column coach – string
Retrieve the details of the account holders who journey is between 2023 – 01 – 01
and 2023 – 12 – 31
import mysql.connector as mycon
con = mycon.connect(host='localhost', user='root', password="5074")
cur = con.cursor()
cur.execute("create database if not exists train")
cur.execute("use train")

cur.execute("create table if not exists passenger_info(pid int not null primary key, pname
varchar(20), pnr_no int , source varchar(50) ,destination varchar(50),train_name
varchar(20),train_no int ,arrival_time time ,journey_date date,distance float ,ticket_price
float )")
con.commit()
s= int(input("Enter passenger ID :"))
n = input("Enter passenger Name : ")
t = int(input("Enter passenger no : "))
f=input("Enter source : ")
m=input("Enter destination : ")
d=input('enter train name : ' )
i=int(input('enter train no : '))
e=input('enter arrival time : ')
j=input('enter the journey date : ')
p=float(input('enter the distance : '))
tp=float(input('enter the ticket price : '))
query="insert into passenger_info values({},'{}',{},'{}','{}','{}',{},'{}','{}',{},
{})".format(s,n,t,f,m,d,i,e,j,p,tp)
cur.execute(query)
con.commit()
print('\n\tdata saved')
q='alter table passenger_info add coach varchar(15)'
cur.execute(q)
l=float(input('enter coach :'))
cur.execute('update passenger_info set coach = {}'.format(l))
con.commit()
q2="SELECT * FROM passenger_info WHERE journey_date BETWEEN '2023-01-01'
AND '2023-12-31'"
cur.execute(q2)
res=cur.fetchall()
print('the passengers whose journey date is between 2023-01-01 AND 2023-12-31')
for i in res:
print(i[0],'\t',i[1],'\t',i[2],'\t',i[3],'\t',i[4],'\t',i[5],'\t',i[6],'\t',i[7],'\t',i[8],'\t',i[9],'\t',i[10],'\t',i[11])
con.close()
---------------------------------------------------------------------------------
---------------------------------------------------------------------------------
---------------------------------------------------------------------------------

You might also like