0% found this document useful (0 votes)
7 views26 pages

CS REcord programs

The document provides detailed instructions for students on how to write and organize their record programs for a Computer Science course. It specifies formatting requirements, the number of programs needed, and guidelines for submission. Additionally, it includes example programs in Python covering various topics such as Fibonacci series, string manipulation, and dictionary operations.

Uploaded by

vishalkarthik.av
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)
7 views26 pages

CS REcord programs

The document provides detailed instructions for students on how to write and organize their record programs for a Computer Science course. It specifies formatting requirements, the number of programs needed, and guidelines for submission. Additionally, it includes example programs in Python covering various topics such as Fibonacci series, string manipulation, and dictionary operations.

Uploaded by

vishalkarthik.av
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/ 26

Dear Students,

Read ALL the instructions, before starting to write the record programs:

Record Instructions:

A) Each program should be written in a new page. (Don't write the programs continuously)

B) Right Side - Use only Blue Gel (same pen) for writing all the exercises. W rite the Ex. No, page number ,
TOPIC(which is given in index ) and Question, then leave one line space and write the program. Draw a line at end of
every program.
C) Left side : Paste the Output.
D) No correction and striking out is allowed
E) Present neatly. Leave spaces wherever required. Write all the programs with proper indentation.

F) Before submitting the record , check whether the following are completed,

1. Seventeen python programs with output and 4 sql programs with output.
2. Brown cover with school label
3. Index to be completed
4. Fill up the index with page numbers

1
D.A.V. PUBLIC SCHOOL,VELACHERY
STD XII – COMPUTER SCIENCE
RECORD PROGRAMS(2023-24)
1. Fibonacci Series and Prime Numbers using Functions:

Aim:
To write a function for the following and get a choice and execute the same from main functions
1. To get a limit and print Fibonacci series in N terms
2. To get two limits and print all prime numbers between the limits
Source code:
def FIBO(n):
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",n,":")
print(0)
else:
print("Fibonacci sequence:")
a, b = 0, 1
for i in range(n):
print(a)
c= a + b
a=b
b=c
def PRIME(lower,upper):
if lower>upper:
lower,upper=upper,lower
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
while True:
print("\n1. Fibonacci series\n2. Prime numbers \n3. Exit\nEnter your Choice(1 to 3)...")
ch=int(input())
if ch==1:
n=int(input("How many terms?"))
FIBO(n)
elif ch==2:
lower=int(input("Enter two limits:"))
upper=int(input())
PRIME(lower,upper)
elif ch==3:

2
break
else: print("Invalid choice")

3
2. Program to Manipulate strings using string functions
Aim:
To write a function that accepts a multiword string as argument, find and print the
number of occurrence and % of occurrence of alphabets, uppercase letters, lowercase letters,
digits, spacesand special characters along with main program.

PROGRAM:

def COUNT_PER(s):
al=uc=lc=di=sp=sc=c=0
for a in s:
if a.isalpha():
al+=1
if a.isupper():
uc+=1
else:
lc+=1
elif a.isdigit():
di+=1
elif a.isspace():
sp+=1
else:
sc+=1
l=len(s)
print("Number of alphabets:",al,"and its % of occurance:",round((al*100/l),2))
print("Number of uppercase letters:",uc,"and its % of occurance:",round((uc*100/l),2))
print("Number of lowercase letters:",lc,"and its % of occurance:",round((lc*100/l),2))
print("Number of digits:",di,"and its % of occurance:",round((di*100/l),2))
print("Number of spaces:",sp,"and its % of occurance:",round((sp*100/l),2))
print("Number of special characters:",sc,"and its % of occurance:",round((sc*100/l),2))

s=input("Enter a sentence:")
COUNT_PER(s)

4
3. Program to print Palindrome Strings, Strings that start with a vowel and strings start
with a consonant from the inputted strings.
Aim:
To write a function that accepts N string values one by one, Count and print number of
palindrome strings, number of vowel strings( string starts with vowel character) and of
consonant strings( string starts with consonant character).
Source Code:
def PALIND(s):
if s==s[::-1]:
return 1
else:
return 0
def CHECK(s):
vow="aeiouAEIOU"
if s.isalpha():
if s[0] in vow:
return 'v'
else:
return 'c'

n=int(input("How many strings?"))


p=v=c=0
print("Enter ", n, " Strings:")
for i in range(n):
a=input()
if PALIND(a)==1:
p+=1
res=CHECK(a)
if res=='v':
v+=1
elif res=='c':
c+=1
print("\n Number of palindrome strings:",p)
print("\n Number of vowel strings:",v)
print("\n Number of consonant strings:",c)’

5
4. Program to print the second Maximum and Second Minimum number in the given list.
Aim:
To write a function that accepts an integer list as argument find and prints the second
maximum and second minimum number in the given list.
SOURCE CODE
def SECOND_MAX_MIN(lis,n):
lis.sort(reverse=True)
for i in range(len(lis)-1):
if lis[i]>lis[i+1]:
print("Second max=",lis[i+1])
break
else:
print("There is no second max as All are equal")

lis.sort()
for i in range(len(lis)-1):
if lis[i]<lis[i+1]:
print("Second min=",lis[i+1])
break
else:
print("There is no second min as All are equal")

a=[]
n=int(input("How many values:"))
print("Enter ",n," values:")
for i in range(n):
a.append(int(input()))
SECOND_MAX_MIN(a,n)

6
5. Program to collect a list as a function argument and shift the odd numbers to the left and even
numbers to the right.
Aim:
To write a function that accepts an integer list as argument and shift all odd
numbers to the left and even numbers to the right of the list without changing the order.

eg. List before shifting: [12,15,10,5,8,9]


List after shifting : [15, 5, 9, 12, 10, 8] )

SOURCE CODE:
def SHIFT(a,n):
c=0
for i in range(n):
if a[i]%2!=0:
x=a.pop(i)
a.insert(c,x)
c+=1

a=[]
n=int(input("How many values:"))
print("Enter ",n," values:")
for i in range(n):
a.append(int(input()))
print("List values before shifting:",a )
SHIFT(a,n)
print("List values after shifting:",a )

7
6. Program to print longest and shortest stings of a tuple and the greatest and the smallest string.

Aim:
To write a function that accepts N strings in a tuple as argument, Find and print the longest
and shortest string of N strings (Lengthwise). Also find and print the greatest and smallest string of N
strings (Alphabetical order) along with main program.

SOURCE CODE:
def FIND_LONG_SHORT(s,n):
long=short=s[0]
for a in s:
if len(a)>len(long):
long=a
elif len(a)<len(short):
short=a
print("Longest string is:",long) ;
print("Shortest string is:",short)

def FIND_GREAT_SMALL(s,n):
great=small=s[0]
for a in s:
if a>great:
great=a
elif a<small:
small=a
print("Greatest string is:",great)
print("Smallest string is:",small)

t=()
n=int(input("How many strings:"))
print("Enter ", n ," Strings:")
for i in range(n):
t+=(input(),)
FIND_LONG_SHORT(t,n)
FIND_GREAT_SMALL(t,n)

8
7. Program to Create a dictionary of Salesman details and print the collected details
along with calculated commission in a tabular view .

Aim:
To write a program to create a dictionary with salesman code as key and a tuple with
elementslike name, product type, sale amount and commission for N salesmen. Also write a
function to display the result as given format. Commission calculation:
Product Type % of commission on Sale s Amount
Medicine 20%
Food 25 %
Garments 18%
other products 15%

Source Code:
def ACCEPT(d,n):
for i in range(n):
t=()
code=int(input("Enter salesman code:"))
t+=(input("Enter name:"),)
t+=(input("Enter Product Type:"),)
t+=(float(input("Enter Purchase Amount:")),)
if t[1].upper()=="MEDICINE":
comm=t[2]*.2
elif t[1].upper()=="FOOD":
comm=t[2]*.25
elif t[1].upper()=="GARMENT":
comm=t[2]*.18
else: comm=t[2]*.15
t+=(comm,)
d[code]=t
def PRINT(d,n):
c=1
print('-'*70)
print("S.No\tCode\tName\tProd Type\tPur. Amt.\tCommission")
print('-'*70)
for i,j in d.items():
print(c,"\t",i,"\t",j[0],"\t",j[1],"\t \t",j[2],"\t\t",j[3])
c+=1

d={}
n=int(input("How many salesmen?"))
ACCEPT(d,n)
PRINT(d,n)

9
8. Program to Create a dictionary for Player details and write a function to arrange
the players in alphabetical order.
Aim:
To write a program to create a dictionary with game as key and list with elements like
player name, country name and points for N players. Write a function to arrange the
players in alphabetical order of game and display the details in the sorted order of game.
Source Code:
def INPUT(d,n):
for i in range(n):
game=input("Enter the game:")
p=list()
p.append(input("Enter player name:"))
p.append(input("Enter Country name:"))
p.append(int(input("Enter the points:")))
d[game]=p
print('-'*100)

def SHOW(d,n):
print("\nRecords in Ascending order of Game:")
for k in sorted(d,reverse= False):
print(k,d[k])
print('-'*100)

d={}
n=int(input("How many Games:"))
INPUT(d,n)
print("Records in DICTIONARY")
print(d)
print('-'*100)
SHOW(d,n)

10
9. Program to Manipulate a dictionary and update the records of the dictionary using
function.
Aim:
To write a program to create a dictionary with game as key and list with elements
like player name, country name and points for N players. Also to write a function to search for
the given country name and print the details of players. The function should also accept the
name of game and update the points by 15% of existing points and display the updated
records.
Source Code:
def INPUT(d,n):
for i in range(n):
game=input("Enter the game:")
p=list()
p.append(input("Enter player name:"))
p.append(input("Enter Country name:"))
p.append(int(input("Enter the points:")))
d[game]=p
print('-'*100)
print("\nRecords in Dictionary")
print(d)
print('-'*100)

def SEARCH(d,n,coun):
flag=0
for key in d.keys():
if d[key][1]==coun:
print(key,d[key])
flag+=1
if flag==0:
print("Searching country not found")
print('-'*100)

def MODIFY(d,n,game):
flag=0
for key in d.keys():
if key==game:
d[key][2]+=d[key][2]*.15
flag+=1
if flag==0:
print("Searching country not found")
else:
print(flag, "Records updated")
print('-'*100)

d={}
n=int(input("How many Games:"))
INPUT(d,n)
coun=input("Enter country name to be searched:")
SEARCH(d,n,coun);
game=input("Enter game name to increase the points:")
MODIFY(d,n,game)
print("Records after updation:")
11
print(d)
print('-'*100)

12
10. Program to work on a text file and copy the content of the text file to another file
based on a given condition.
Aim:
To write a program with functions to create a text file called school.txt, store
information and print the same. Also to write another function to copy all the lines to the
new file called myschool.txt which do not have the word ‘It’ anywhere in the line and
display the new file.
Source Code
def CREATE():
f=open("school.txt","w")
print("Enter information about school and 'exit' to stop")
while True:
s=input()
if s.upper()=='EXIT':
break
f.write(s)
f.write('\n')
f.close()
def PRINT(a):

f=open(a,"r") s=" "


while s:
s=f.readline()
print(s,end="")
f.close()

def COPY():
f1=open("school.txt","r")
f2=open("myschool.txt","w")
s=" "
while s:
s=f1.readline()
if 'It'.upper() in s.upper():
pass
else:
f2.write(s)
f1.close()
f2.close()

CREATE()
print("CONTENT OF SCHOOL.TXT FILE:")
PRINT("school.txt")
COPY()
print("CONTENT OF MYSCHOOL.TXT FILE:")
PRINT("myschool.txt")

13
11.Program to create a text file and print the 5 most common words of the text file:
Aim:
To write function to create a text file called marina.txt to store information about
marina beach,read the data, find and print the occurrence of most 5 common words present in
the file.

Source Code:
def CREATE():
f=open("marina.txt","w")
print("Enter information about marina beach and 'exit' to stop:")
while True:
s=input()
if s.upper()=='EXIT':
break
f.write(s)
f.write('\n')
f.close()
def PRINT():
f=open("marina.txt","r")
s=" "
print("FILE CONTENT:")
while s:
s=f.readline()
print(s,end="")
f.close()

def Find_Common():
f=open("marina.txt","r")
s=" "
d=dict()
while s:
s=f.readline()
s=s.rstrip("\n")
a=s.split()
for i in a:
if i in d.keys():
d[i]+=1
else:
d[i]=1 # first occurance
c=0
print("\nCommon Frequency of 5 words:")
for k in sorted(d, key=d.get, reverse=True):
print(k,"\t:",d[k]) #
c+=1
if c==5:
break
f.close()

CREATE()
PRINT()
Find_Common()

14
12. Working with a Binary File- I
Aim: To work with the Binary File emp.dat[empno, empname,salary] and write a user
defined functionCreateEmp() to input data for a record and add to emp.dat and display the
details using DISPLAY() function Also to write Search() function that would read contents
of the file emp.dat and display the details of those employees whose salary is greater than
10000.
SORCE CODE

import pickle
def validate_empno():
with open("emp.dat",'rb') as f:
en=int(input("Enter emp no."))
try:
while True:
a = pickle.load(f)
if en == a[0]:
print("\nEmp no. is already exists!!!")
return -1
except EOFError:
return en

def CreateEmp():
with open("emp.dat",'wb') as f:
n=int(input("Enter how many employees"))
for i in range(n):
lis=[]
eno=validate_empno()
if eno==-1:
break
ename=input("Enter employee name")
salary=int(input("Enter basic salary"))
lis=[eno,ename,salary]
pickle.dump(lis,f)
f.flush()
f.close()

def DISPLAY():
with open("emp.dat",'rb') as f:
print("\nContents of the file")
print("\nEMPNO\tEMPNAME\tSALARY")
try:
while True:
a = pickle.load(f)
print(a[0],a[1],a[2],sep='\t')
except EOFError:
return

15
def Search():
with open("emp.dat",'rb') as f:
print("\nSalary more than 10000")
print("\nEMPNO\tEMPNAME\tSALARY")
try:
while True:
a = pickle.load(f)
if a[2]>10000:
print(a[0],a[1],a[2],sep='\t')
except EOFError:
return
CreateEmp()
DISPLAY()
Search()

16
13. Working with Binary Files – II

Aim: To create a binary file “emp.dat” [empno, empname,salary]. To write a user defined
function CreateEmp() to input data for a record and add to emp.dat , DELETE() to accept an
employee number and delete the details. Function should display the file contents before and
after deletion of employee record using DISPLAY() function.
SOURCE CODE:
import pickle
import os
def validate_empno():
with open("emp.dat",'rb') as f:
en=int(input("Enter emp no."))
try:
while True:
a = pickle.load(f)
if en == a[0]:
print("\nEmp no. is already exists!!!")
return -1
except EOFError:
return en
def CreateEmp():
f=open("emp.dat",'wb')
n=int(input("Enter how many employees"))
for i in range(n):
lis=[]
eno=validate_empno()
if eno==-1:
break
ename=input("Enter employee name")
salary=int(input("Enter basic salary"))
lis=[eno,ename,salary]
pickle.dump(lis,f)
f.flush()
f.close()

def DISPLAY():
with open("emp.dat",'rb') as f:
print("\nContents of the file")
print("\nEMPNO\tEMPNAME\tSALARY")
try:
while True:
a = pickle.load(f)
print(a[0],a[1],a[2],sep='\t')
except EOFError:
return

17
def DELETE():
flag=0
en=int(input("Enter the emp no. to delete"))
with open("emp.dat",'rb') as f, open("tem.dat",'wb') as f2:
try:
while True:
a = pickle.load(f)
if en != a[0]:
pickle.dump(a,f2)
f2.flush()
else:
flag=1
except EOFError:
pass
if flag==0:
print("\nEmp no. is not found!")
return
else:
print("\nRecord is deleted!")
os.remove('emp.dat')
os.rename('tem.dat','emp.dat')

CreateEmp()
DISPLAY()
DELETE()
print("\nAfter Delete")
DISPLAY()

18
14. Working with a CSV File -I
Aim: To write a function create() to create CSV file student.csv which accepts rollno,name,sec and
average marks for N students. Also to write 2 more functions show() and show2() to display all the
details and to display the students those who have got the average marks greater than or equal to 80,
respectively.
Source Code:
import csv
def create():
f=open("student.csv",'w',newline="")
writer=csv.writer(f)
writer.writerow(["\nrollno",'name','section','Avg_marks\n'])
while True:
r=int(input("Enter the rollno:"))
n=input("Enter the name:")
g=input("Enter the section:")
m=int(input("Enter the Avg marks:"))
data=[r,n,g,m]
writer.writerow(data)
ch=input("press any key to continue?N to exit\n")
if ch in 'nN':
break
f.close()

def show():
f=open("student.csv",'r')
reader=csv.reader(f)
for a in reader:
print(a[0],a[1],a[2],a[3],sep='\t')
f.close()
def show2():
f=open("student.csv",'r')
reader=csv.reader(f)
header=next(reader) # to skip headings, next() returns first row to header

for a in reader: # iterate from second row


if int(a[3]) >=80: # int() fn is given as the data stored always as string in csv
print(a[0],a[1],a[2],a[3],sep='\t')
f.close()

create()
print("All the students details")
show()
print("\nStudents who have got average >=80\n")
show2()
19
15. Working with a CSV File- II

Aim : To write a function create() to create “password.csv” which accepts user id and
password. Write function show() to display all the details, show2() to accept the user id
and print the password if the user id is present otherwise print the error message 'user id
is not present”
SOURCE CODE
import csv
def create():
f=open("password.csv",'w',newline="")
writer=csv.writer(f)
writer.writerow(["User Name",'Password'])
while True:
r=input("Enter the User id:")
n=input("Password:")
data=[r,n]
writer.writerow(data)
ch=input("press any key to continue?N to exit\n")
if ch in 'nN':
break
f.close()

def show():
f=open("password.csv",'r')
reader=csv.reader(f)
for a in reader:
print(a[0],'\t',a[1])

f.close()

def show2():
f=open("password.csv",'r')
id=(input("Enter the User id to search password:"))
reader=csv.reader(f)
for a in reader:
if a[0]==id:
print("Password :",a[1])
break
else:
print("User id is not present")
f.close()

create()
show()

20
16. Stack Application
Aim : To write a Menu driven Code to implement Stack Operations like Push, Pop and display the stack
after the operations
SPURCE CODE

def PUSH(L):
for i in L:
if i%3==0:
only_3.append(i)

#display the list only_3


if only_3==[]:
print("No numbers are divisible by 3")
else:
print("Pushed values which are divisible by 3:",end=' ')
for i in only_3:
print(i,end=' ')

def POP():
print("Poped values are:",end=' ')
while only_3: #empty list returns false
print(only_3.pop(), end=' ')
print("Stack is empty")

num=[]
only_3=[]

n=int(input("How many numbers?"))


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

while True:
print("\n1. PUSH\n2. POP\n3. Exit")
ch=int(input("Enter Your choice:"))

if ch==1:
PUSH(num)
elif ch==2:
POP()
elif ch==3:
break
else:
print("Invalid choice")

21
SQL
17.SQL Connectivity I
Aim : Write a program to connect Python with MYSQL using database connectivity for the table STUDENT
given below and perform the following.

Roll Name Stipend Stream Avgmark Grade Class

101 Karan 400 Medical 78.5 B 12


102 Divakar 450 Commerce 89.2 A 11
103 Divya 300 Commerce 68.6 C 12
104 Arun 350 Medical 85.5 D 12
105 Sophy 600 Biology 90.3 A 11

1. Select all the medical stream student from the student table.
2. To display stream and number of students in each stream of the given table student.
3. List the name and grade whose avgmark is above 85.
4. Display the total of stipend whose grade is A.
5. To increase the stipend by 200 whose grade is A.
PROGRAM:
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='root',charset='utf8')
cur=con.cursor()

cur.execute("create database if not exists practical")


cur.execute("use practical")

cur.execute("create table if not exists student (roll int primary key, name char(20),stipend int, stream
char(10), avgmark int, grade char, class int)")
print("Table created")

cur.execute("insert ignore into student values(101,'Karan',400,'Medical', 78.5,'B',12)")


cur.execute("insert ignore into student values(102,'Divakar',450,'Commerce', 89.5,'A',11)")
cur.execute("insert ignore into student values(103,'Divya',300,'Commerce', 68.6,'C',12)")
cur.execute("insert ignore into student values(104,'Arun',350,'Medical', 85.5,'D',12)")
cur.execute("insert ignore into student values(105,'Sophy',600,'Biology', 90.3,'A',11)")

con.commit()
print("Records inserted")

print("1.")
cur.execute("select * from STUDENT where STREAM='Medical' ")
data=cur.fetchall()
for x in data:
print(x)

print("2.")
cur.execute("select STREAM, count(*) from STUDENT group by STREAM")
for x in cur:
print(x)

print("3.")
22
cur.execute("select NAME, GRADE from STUDENT where AVGMARK>85")
for x in cur:
print(x)

print("4.")
cur.execute("select sum(stipend) from STUDENT where grade = 'A' ")
for x in cur:
print(x[0])

print("5.")
cur.execute("update student set stipend=stipend+200 where grade='A' ")
print("Record updated")
con.commit()
cur.close()
con.close()

SQL Connectivity II
18.
Aim : To write a program to connect Python with MYSQL using database connectivity for the table
SALES givenbelow and perform the following.

NAME PRODUCT QTY_TAR PRICE COMMISSION

Santhosh Lux 50 15.35 120


Praveen Harpic 25 40.25 150
Kumar Britannia 20 11.25 100
Arjun Glaxo 30 67.85 150
Jacob Hamam 40 11.50 200

1. Display all the records of those QTY_TAR is more than 35 and arranged by ascending order of product.
2. Select the name and product where the product as Britannia and the commission>=100
3. To display the number of tuples available in the table.
4. Select and display the maximum price and minimum price of the table sales.
5. Delete the record whose commission is 150.
PROGRAM :
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='root',charset='utf8')
cur=con.cursor()

cur.execute("create database if not exists practical")


cur.execute("use practical")
cur.execute("create table if not exists sales(Name char(20) not null, product char(10), Qty_tar int, price
double, commission int)")
print("Table created")

cur.execute("insert ignore into sales values('Santhosh','Lux',50,15.35,120)")


cur.execute("insert ignore into sales values('Praveen','Harpic',25,40.25,150)")
cur.execute("insert ignore into sales values('Kumar','Britannia',20,11.25,100)")
cur.execute("insert ignore into sales values('Arjun','Glaxo',30,67.85,150)")
cur.execute("insert ignore into sales values('Jacob','Hamam',40,11.50,200)")

23
con.commit()
print("Records inserted")

print("1.")
cur.execute("select * from SALES where QTY_TAR>35 order by PRODUCT ")
for x in cur:
print(x)
print("2.")
cur.execute(" select NAME, PRODUCT from SALES where PRODUCT ='Britannia' and
COMMISSION>=100")
for x in cur:
print(x)
print("3.")
cur.execute("select count(*) from SALES ")
for x in cur:
print(x)
print("4.")
cur.execute("select max(price), min(price) from SALES")
for x in cur:
print(x)
print("5.")
cur.execute("delete from sales where commission=150")
print("Record Deleted")

con.commit()
cur.close()
con.close()

19. SQL Connectivity III

Aim : To write a program to connect Python with MYSQL using database connectivity for the table MOVIE
given below and perform the following.

TITLE TYPE RATING STARS QTY PRICE

Liar Liar Comedy PG13 Jim Carre 5 25.35


Lost World Horror PG Melgibson 4 35.45
The specialist Action G Stallon 3 40.23
Down Periscope Comedy PG13 Stone 6 43.25
Conair Action G Nicholas 3 55.25

1. Display the maximum price from movie table.


2. List all the stars name starts with ‘S’.
3. Display all the details arranged by ascending order of title.
4. Display the title where price is more than 20.
5. To change the value of quantity as 10 those movie type is comedy.
PROGRAM:
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='root',charset='utf8')
cur=con.cursor()

cur.execute("create database if not exists practical")

24
cur.execute("use practical")

cur.execute("create table if not exists movie (title char(20) primary key, type char(10), rating char(15), stars
char(10), qty int, price float)")
print("Table created")

cur.execute("insert ignore into movie values('Liar Liar','Comedy','PG13','JimCarre',5,25.35)")


cur.execute("insert ignore into movie values('Lost World','Horror','PG','Melgibson',4,35.45)")
cur.execute("insert ignore into movie values('The specialist','Action','G','Stallon',3,40.23)")
cur.execute("insert ignore into movie values('Down Periscope','Comedy','PG13','Stone',6,43.25)")
cur.execute("insert ignore into movie values('Conair','Action','G','Nicholas',3,55.25)")
con.commit()
print("Records inserted")

print("1.")
cur.execute("select max(price) from movie")
for x in cur:
print(x)

print("2.")
cur.execute("select stars from MOVIE where STARS like 'S%'")
for x in cur:
print(x)

print("3.")
cur.execute("select * from MOVIE order by TITLE ")
for x in cur:
print(x)
print("4.")
cur.execute("select TITLE from MOVIE where PRICE>20")
for x in cur:
print(x)

print("5.")
cur.execute("update movie set qty=10 where type='comedy' ")
print("Record updated")
con.commit()
cur.close()
con.close()

20. SQL Connectivity IV

Aim : To write a program to connect Python with MYSQL using database connectivity for the table
LIBRARYgiven below and perform the following.

BID TITLE AUTHOR TYPE PUB QTY PRICE

101 Data structure Lipchutz DS McGraw 4 217


102 Advanced Pascal Schildt PROG BPB 5 350
103 Mastering C++ Gurewich PROG PHI 3 130
104 Mastering Window Cowart OS BPB 6 40
105 Network Guide Freed NET Zpress 5 200

25
1. Display all the details of those type is PROG and publisher is BPB.
2. Display all the details with price more than 130 and arranged by ascending order of qty.
3. Display the number of books published by BPB.
4. Display the title and qty for those qty between 3 and 5.
5. Delete the record whose type is PROG.
PROGRAM:
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='root',charset='utf8')
cur=con.cursor()
cur.execute("create database if not exists practical")
cur.execute("use practical")
cur.execute("create table if not exists library (bid int primary key, title char(20) not null ,author char(10),
type char(10), pub char(10), qty int, price int)")
print("Table created")

cur.execute("insert ignore into library values(101,'Data structure','Lipchutz','DS','McGraw',4,217)")


cur.execute("insert ignore into library values(102,'AdvancedPascal','Schildt','PROG','BPB',5,350)")
cur.execute("insert ignore into library values(103,'Mastering C++','Gurewich','PROG','PHI',3,130)")
cur.execute("insert ignore into library values(104,'Mastering Window','Cowart','OS','BPB',6,40)")
cur.execute("insert ignore into library values(105,'Network Guide','Freed','NET','Zpress',5,200)")

con.commit()
print("Records inserted")

print("1.")
cur.execute("select * from library where TYPE='PROG' and PUB ='BPB' ")
for x in cur:
print(x)

print("2.")
cur.execute("select * from library where PRICE>130 order by QTY ")
for x in cur:
print(x)

print("3.")
cur.execute("select count(*) from library where PUB='BPB' ")
for x in cur:
print(x)

print("4.")
cur.execute("select title,qty from library where qty between 3 and 5")
for x in cur:
print(x)

print("5.")
cur.execute("delete from library where type='PROG' ")
print("Record deleted")
con.commit()
cur.close()
con.close()

26

You might also like