0% found this document useful (0 votes)
31 views50 pages

Cs Practical File Vibhu

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)
31 views50 pages

Cs Practical File Vibhu

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/ 50

ST. MARY’S CONVENT SR. SEC.

SCHOOL,
GAJRAULA

COMPUTER SCIENCE PRACTICAL FILE


SESSION 2023-24

SUBMITTED BY- SUBMITTED TO-

NAME- VIBHU KAKKAR MA’AM BINDU


CLASS- XII
ROLL. NO. -

1
INDEX
S.NO. TOPIC PAGE NO.
1. PYTHON FUNCTION 3-15

2. FILE HANDLING 16-27

3. DATA STRUCTURE 28-34

4. DATABASES 35-46

5. INTERFACE PYTHON 46-50


WITH MYSQL

2
PYTHON FUNCTIONS

1- Write a function to check whether the number is an


Armstrong number.

def Armstrong(x):
s=0
a=x
while x>0:
k=x%10
s=(s+k)**3
x=x//10
if s==a:
print(“The number is Armstrong”)
else:
print(“The number is not Armstrong”)

2- Write a function to check whether the string is


palindrome or not.

def Palindrome(s):
y=""
for i in range(len(s)-1,-1,-1):
y=y+s[i]
if (y==s):
print(“The string is palindrome”)
else:
print(“The string is not a palindrome”)

3
3- Write a function to count the number of vowels and
consonants in a string.

def string(s):
v=c=0
for i in s:
if i.isalpha():
if i in "AaEeIiOoUu":
v=v+1
else:
c=c+1
print(“number of vowels”,v)
print(“number of consonants”,c)

4- Write a function to pass a list and a number, search


for the number in a list.

def Lsearch(L,val):
if val in L:
print(“found”)
else:
print(“Not found”)

5- Write a function to pass the string and return a


reversed string.

def Sreverse(str):
y=""
for i in range(len(str)-1,-1,-1):
y=y+str[i]
return(y)

4
6-Write a function to print the sum of digits in a
passed number.

def sumdigit(n):
s=0
while n>0:
k=n%10
s=s+k
n=n//10
return(s)

7-Write a function to pass a list and return a reversed


list.

def revlist(L):
L.reverse()
return(L)

8-Write a function to pass a list. If the elements are


even multiply by 3 otherwise multiply by 5.

def xyz(L):
for i in range(0,len(L)):
if L[i]%2==0:
L[i]*=3
else:
L[i]*=5
print(L)

5
9-Write a function to pass two parameters x and n as
integers. Calculate the following sum of series and
return the value:-
2 3 n
1+ x/2! + x /4! + x /6! +………x /2n!

def sumofseries(x,n):
s=0
for i in range(0,n+1):
F=1
for j in range (1,2*i+1):
F=F*j
s=s+(x**i)/F
print("Sum of series=",s)

10- Write a function power(x,n) where x and n are


integers. Calculate xn and return the result.

def power(x,n):
y=x**n
return(y)

11- Write a function which consists of list of integers as


parameter. Interchange even element location with
the odd location element.

def location(L):
for i in range(0,len(L)-1):
if i%2==0:
L[i],L[i+1]=L[i+1],L[i]
print(L)

6
12- Write a function to search an element in a list. If
found replace it by 0 and move all the 0 to the
beginning of the list.

def func(L,n):
k=0
for i in range(len(L)):
if L[i]==n:
L[i]=0
for j in range(i,k,-1):
L[j],L[j-1]=L[j-1],L[j]
k=k+1
print(L)

13- Write a function to display the fibonacci series.

def fibonacci(n):
n1,n2=0,1
print(n1,n2,end=" ")
for i in range(2,n):
n3=n1+n2
n1=n2
n2=n3
print(n3,end=" ")

14- Write a function to accept ‘p’ as principle amount,


‘r’ as rate and ‘t’ as time, calculate and return simple
interest, ‘SI’.

def SI(P,R,T):
S=(P*R*T)/100
return(S)

7
15- Write a function to accept a 2d list. Display the
sum of even elements of the 2d list.
def xyz():
l=[]
for i in range(r):
row=[]
for j in range(c):
x=int(input("Enter a no."))
row.append(x)
l.append(row)
s=0
for i in range(r):
for j in range(c):
if l[i][j]%2==0:
s+=l[i][j]
print(“Sum of even elements”,s)

16- Write a function to accept a 2d array. Find the


sum of those elements which ends with 3.
def abc():
l=[]
for i in range(r):
row=[]
for j in range(c):
x=int(input("Enter a no."))
row.append(x)
l.append(row)
s=0
for i in range(r):
for j in range(c):
if l[i][j]%10==3:
s+=l[i][j]
print(“Required sum”,s)

8
17- Write a function to check whether the number is
prime or not.
def prime(n):
k=0
for i in range(2,n):
if n%i==0:
k=1
if k==0:
print("It is a prime number")
else:
print("It is not a prime number")

18- Write a function to print the maximum number.


def MAX(A,B,C):
if A>B and A>C:
print("Maximum number - ",A)
elif B>A and B>C:
print("Maximum number - ",B)
elif C>A and C>B:
print("Maximum number - ",C)

19- Write a function to print the multiplication table


of a number.
def MTABLE(N):
for i in range(1,11):
print(N,"x",i,"=",N*i)

20- Write a function to print the sum of natural


numbers till N.
def NSUM(N):
S=0
for i in range(1,N+1):
S=S+i
print("SUM OF NATURAL NUMBER :",S)

9
CALLING STATEMENTS wITH THEIR
OUTPUTS
1-ARMSTRONG NUMBER
x=int(input("Enter a number"))
Armstrong(x)
OUTPUT
Enter a number 153
The number is Armstrong

2-PALINDROME SERIES
s=input("Enter a string")
Palindrome(s)
OUTPUT
Enter a string madam
The string is palindrome

3-VOWELS AND CONSONANTS IN A STRING


x=input("Enter a string")
string(x)
OUTPUT
Enter a string Python is a computer language
number of vowels 11
number of consonants 14

4- SEARCH FOR A NUMBER IN A LIST


L=eval(input("Enter a list"))
val=int(input("value to be search"))
Lsearch(L,val)
OUTPUT
Enter a list [2,4,7,9,5]
value to be search 2
10
found
5-REVERSED STRING
x=input("Enter a string")
s=Sreverse(x)
print(“Reversed string”,s)
OUTPUT
Enter a string python
Reversed string nohtyp

6- SUM OF DIGITS IN A NUMBER


n=int(input("Enter a number"))
y=sumdigit(n)
print("Sum of digit",y)
OUTPUT
Enter a number 207
Sum of digits 9

7- REVERSED LIST
L=eval(input("Enter a list"))
print(revlist(L))
OUTPUT
Enter a list [1,2,3,4,5]
[5, 4, 3, 2, 1]

8- IF ELEMENTS OF THE LIST ARE EVEN MULTIPLY BY 3


OTHERWISE MULTIPLY BY 5
x=eval(input("Enter a list"))
xyz(x)
OUTPUT
Enter a list [2,3,4,5,6,7]
[6,15,12,25,18,35]

11
9-SUM OF SERIES:-
1+ x/2! + x2/4! + x3/6! +………xn/2n!
x=int(input("Enter a number="))
n=int(input("Enter a number="))
sumofseries(x,n)
OUTPUT
Enter a number= 5
Enter a number= 5
Sum of series= 4.731639936067019

10-POWER FUNCTION (xn)


x=int(input("Enter a number"))
a=power(x,n=2)
print(a)
OUTPUT
Enter a number 5
25

11- INTERCHANGE EVEN LOCATION ELEMENT TO ODD


LOCATION ELEMENT OF A LIST
x=eval(input("Enter a list"))
location(x)
OUTPUT
Enter a list [2,3,4,5,6,7]
[3, 2, 5, 4, 7, 6]

12- REPLACE THE SEARCHED ELEMENT BY 0 AND MOVE ALL


THE 0 AT THE BEGINNING OF THE LIST
L=eval(input("Enter a list"))
n=int(input("Enter no. to be searched"))
func(L,n)
OUTPUT
Enter a list [1,2,3,5,2,2,6,2,7,2]
Enter no. to be searched 2
12
[0, 0, 0, 0, 0, 1, 3, 5, 6, 7]
13- FIBONACCI SERIES
n=int(input("Enter the no. of times"))
fibonacci(n)
OUTPUT
Enter the no. of times 10
0 1 1 2 3 5 8 13 21 34

14- SIMPLE INTEREST


P=int(input("Enter principle amount"))
R=int(input("Enter Rate"))
T=int(input("Enter time period"))
print("Simple interest",SI(P,R,T))
OUTPUT
Enter principle amount 2000
Enter Rate 5
Enter time period 4
Simple interest 400.0

15- SUM OF EVEN ELEMENT OF 2D LIST


r=int(input("Enter no. of rows"))
c=int(input("Enter no. of columns"))
xyz()
OUTPUT
Enter no. of rows 3
Enter no. of columns 3
Enter a no. 1
Enter a no. 2
Enter a no. 3
Enter a no. 4
Enter a no. 5
Enter a no. 6
Enter a no. 7
Enter a no. 8
Enter a no. 9
13
Sum of even elements 20

16- SUM OF THOSE ELEMENT IN 2D LIST WHICH ENDS WITH


3
r=int(input("Enter no. of rows"))
c=int(input("Enter no. of columns"))
abc()
OUTPUT
Enter no. of rows 3
Enter no. of columns 3
Enter a no. 1
Enter a no. 2
Enter a no. 3
Enter a no. 33
Enter a no. 5
Enter a no. 6
Enter a no. 13
Enter a no. 2
Enter a no. 5
Required sum 49

17- PRIME NUMBER


n=int(input("Enter a number "))
prime(n)
OUTPUT
Enter a number 53
It is a prime number

18- MAXIMUM NUMBER


A=int(input("Enter first number "))
B=int(input("Enter second number "))
C=int(input("Enter third number "))
MAX(A,B,C)
OUTPUT
Enter first number 10
14
Enter second number 50
Enter third number 30
Maximum number - 50

19- MULTIPLICATION TABLE


N=int(input("Enter the number "))
MTABLE(N)
OUTPUT
Enter the number 2
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

20- SUM OF NATURAL NUMBERS TILL N


N=int(input("Enter the number "))
NSUM(N)
OUTPUT
Enter the number 5
SUM OF NATURAL NUMBER : 15

15
FILE HANDLING
TEXT FILES FUCTIONS
NOTES.TXT FILE CONTENTS
Data Files-
Data files are the files that store data pertaining to a specific application for later
use. The data files can be stored in two ways-
1- Text files - A text file stores information in the form of a stream of ASCII or
Unicode characters. In this each line is terminated of text with a special
character known as EOL (End of line).
2- Binary files – A binary file stores the information in the form of a stream of
bytes. A binary files contains information in the same format in which
information is held in memory. There is no delimiter for a line.

21-Write a function to read the file notes.txt using


readlines and display its content on the screen.
def abc():
xf=open("notes.txt","r")
y=xf.readlines()
for i in y:
print(i)
xf.close()
22-Write a function to read a file notes.txt, count the
number of words in the file.
def xyz():
xf=open("notes.txt","r")
y=' '
c=0
while y:
y=xf.readline()
l=y.split()
c=c+len(l)
print("No. of words=",c)
xf.close()
16
23-Write a function to read the file Notes.txt , count
number of lines in the file.
def countlines():
xf=open("Notes.txt","r")
y=len(xf.readlines())
print("Total number of lines = ",y)
xf.close()

24-Write a function to read the file notes.txt , count


number of words starting with vowels and consonants.
def count():
xf=open("notes.txt","r")
y=' '
l=[]
c=v=0
while y:
y=xf.readline()
l=y.split()
for i in l:
if i[0].isalpha():
if i[0] in "AaEeIiOoUu":
v=v+1
else:
c=c+1
print("No. of words starting with vowels =",v)
print("No. of words starting with consonants =",c)
xf.close()

25-Write a function to read a file notes.txt and count


the number of words which have 3 or 5 characters.

17
def characters():
xf=open("notes.txt","r")
y=' '
l=[]
c=0
while y:
y=xf.readline()
l=y.split()
for i in l:
if len(i)==3 or len(i)==5:
c=c+1
print("Required characters =",c)
xf.close()

CALLING STATEMENTS wITH THEIR


OUTPUTS
21- READ A FILE USING READLINES AND DISPLAY ITS
CONTENTS
abc()
OUTPUT
Data Files-
Data files are the files that store data pertaining to a specific application for later
use. The data files can be stored in two ways-
1- Text files - A text file stores information in the form of a stream of ASCII or
Unicode characters. In this each line is terminated of text with a special
character known as EOL (End of line).
2- Binary files – A binary file stores the information in the form of a stream of
bytes. A binary files contains information in the same format in which
information is held in memory. There is no delimiter for a line.

22- COUNT THE NUMBER OF WORDS IN THE FILE


xyz()
18
OUTPUT
No. of words= 106

23- COUNT THE NUMBER OF LINES IN THE FILE


countlines()
OUTPUT
Total number of lines = 4

24- COUNT THE NUMBER OF WORDS STARTING WITH


VOWELS AND CONSONENTS
count()
OUTPUT
No. of words starting with vowels = 37
No. of words starting with consonants = 65

24- COUNT THE NUMBER OF WORDS WHICH HAVE 3 OR 5


CHARACTERS
characters()
OUTPUT
Required characters = 27

19
BINARY FILES

29 - Write a program to create the details of a


stationary shop with the following modules-
1- Adding records
2- Modifying records
3- Search for a particular record
4- Removal of unwanted information
5- Displaying reports
6- Exit

import pickle
import os
def add():
xf=open('stationary.txt',"ab")
IT={}
wish='Y'
while wish=='Y':
itno=int(input("Enter item number "))
desc=input("Enter item name ")
qty=int(input("Enter item quantity "))
rate=float(input("Enter rate "))
IT['INO.']=itno
IT['Description']=desc
IT['Quantity']=qty
IT['Rate']=rate
IT['Amt']=qty*rate
pickle.dump(IT,xf)
wish=input("Add more Y/N ")
xf.close()
import pickle
def modify():

20
Found=False
xf=open('stationary.txt',"rb+")
IT={}
try:
N=int(input("Enter the item number to be modified "))
while True:
rec=xf.tell()
IT=pickle.load(xf)
if IT['INO.']==N:
rate=float(input("Enter new rate "))
IT['Rate']=rate
IT['Amt']=rate*IT['Quantity']
print(IT)
break
xf.seek(rec)
pickle.dump(IT,xf)
Found=True
except EOFError:
if Found==False:
print("No such record")
xf.close()
import pickle
def search():
xf=open('stationary.txt',"rb")
Found=False
IT={}
N=int(input("Enter the item number "))
try:
while True:
IT=pickle.load(xf)
if IT['INO.']==N:
print(IT)
Found=True
except EOFError:

21
if Found==False:
print("No such record")
xf.close()
import pickle
def delete():
yf=open('temp.dat',"wb")
xf=open('stationary.txt',"rb")
Found=False
IT={}
N=int(input("Enter the item number "))
try:
while True:
IT=pickle.load(xf)
if IT['INO.']!=N:
pickle.dump(IT,xf)
else:
Found=True
except EOFError:
if Found==False:
print("Not found")
xf.close()
yf.close()
os.remove("stationary.txt")
os.rename("temp.txt","stationary.txt")
import pickle
def display():
xf=open('stationary.txt',"rb")
IT={}
try:
while True:
IT=pickle.load(xf)
print(IT)
except EOFError:
xf.close()

22
while True:
print("\t\t\t\t XYZ stationary")
print("\t 1. Adding records")
print("\t 2. Modification of records")
print("\t 3. Searching particular details")
print("\t 4. Deleting record")
print("\t 5. Report")
print("\t 6. End of program")
ch=int(input("Enter your choice : "))
if ch==1:
add()
elif ch==2:
modify()
elif ch==3:
search()
elif ch==4:
delete()
elif ch==5:
display()
elif ch==6:
print("END OF PROGRAM")
break
else:
print("Wrong choice enter again")

OUTPUT
XYZ stationary
1. Adding records
2. Modification of records
3. Searching particular details
4. Deleting record
5. Report

23
6. End of program
Enter your choice : 1
Enter item number 1
Enter item name Pen
Enter item quantity 5
Enter rate 100
Add more Y/N Y
Enter item number 2
Enter item name Pencil
Enter item quantity 10
Enter rate 100
Add more Y/N Y
Enter item number 3
Enter item name Copy
Enter item quantity 2
Enter rate 200
Add more Y/N N
XYZ stationary
1. Adding records
2. Modification of records
3. Searching particular details
4. Deleting record
5. Report
6. End of program
Enter your choice : 2
Enter the item number to be modified 3
Enter new rate 100
{'INO.': 3, 'Description': 'Copy', 'Quantity': 2, 'Rate': 100.0, 'Amt': 200.0}
XYZ stationary
1. Adding records
2. Modification of records
3. Searching particular details
4. Deleting record
5. Report

24
6. End of program
Enter your choice : 3
Enter the item number 1
{'INO.': 1, 'Description': 'Pen', 'Quantity': 5, 'Rate': 100.0, 'Amt': 500.0}
XYZ stationary
1. Adding records
2. Modification of records
3. Searching particular details
4. Deleting record
5. Report
6. End of program
Enter your choice : 5
{'INO.': 1, 'Description': 'Pen', 'Quantity': 5, 'Rate': 100.0, 'Amt': 500.0}
{'INO.': 2, 'Description': 'Pencil', 'Quantity': 10, 'Rate': 100.0, 'Amt':
1000.0}
{'INO.': 3, 'Description': 'Copy', 'Quantity': 2, 'Rate': 200.0, 'Amt': 400.0}
XYZ stationary
1. Adding records
2. Modification of records
3. Searching particular details
4. Deleting record
5. Report
6. End of program
Enter your choice : 6
END OF PROGRAM

25
CREATION OF CSV FILES

27-Write a program to create a csv file to store employ


data (Empno, Name, Salary). Obtain the data from
user and write 5 records into the file emp.csv.
import csv
xf=open("emp.csv","w")
obj=csv.writer(xf)
obj.writerow(['Empno','Name','Salary'])
for i in range(5):
Empno=int(input("Enter employ number "))
Name=input("Enter name ")
Salary=float(input("Enter Salary "))
obj.writerow([Empno,Name,Salary])
xf.close()

OUTPUT
Enter employ number 1001
Enter name Ram
Enter Salary 70000
Enter employ number 1002
Enter name Siya
Enter Salary 60000
Enter employ number 1003
Enter name Sam
Enter Salary 55000
Enter employ number 1004
Enter name Ansh
Enter Salary 50000
Enter employ number 1005
Enter name Raj
Enter Salary 75000

26
READING OF CSV FILE

28-Write a program to read the records of emp.csv file


and display them.
import csv
xf=open("emp.csv","r",newline="\r\n")
rec=csv.reader(xf)
for i in rec:
print(i)
xf.close()

OUTPUT
['Empno', 'Name', 'Salary']
['1001', 'Ram', '70000.0']
['1002', 'Siya', '60000.0']
['1003', 'Sam', '55000.0']
['1004', 'Ansh', '50000.0']
['1005', 'Raj', '75000.0']

27
DATA STRUCTURE
LINEAR SEARCH AND BINARY SEARCH

29 (i.) -Write a function L.Search(L,Val) where L is the


list of integers and val is integer value passed as
argument, search for val in list, if found return 1
otherwise return 0.

def Lsearch(l,val):
k=0
for i in l :
if i==val:
k=1
break
return(k)
l=eval(input("Enter the list of numbers "))
m=int(input("Enter the value to be search "))
k=Lsearch(l,m)
if k ==1:
print("Found")
else:
print("Not Found")
Lsearch(l,m)

OUTPUT
Enter the list of numbers [20,55,70,45,80]
Enter the value to be search 70
Found

28
29 (ii.)-Write a function B.Search(L,Val) where L is
passed as list of integers and val is the number to be
search in the list.

def Bsearch(l,val):
k=0
beg=0
last=len(l)-1
while beg <=last:
mid=(beg+last)//2
if l[mid]==val:
k=1
break
elif l[mid]>val:
last=mid-1
elif l[mid]<val:
beg=mid+1
return(k)
l=eval(input("Enter the list of numbers "))
n=int(input("Enter value to be search "))
if Bsearch(l,n)==1:
print("Found")
else:
print("Not found")
Bsearch(l,n)

OUTPUT
Enter the list of numbers [25,40,55,67,90]
Enter value to be search 55
Found

29
BUBBLE SORT AND INSERTION SORT
30 (i.) -Write a function Bsort(L) where L is the list of
integers passed as the arguments. Arrange the data in
ascending order using bubble sort.
def Bsort(L):
for i in range(0,len(L)):
for j in range(0,len(L)-1-i):
if L[j]>L[j+1]:
L[j],L[j+1]=L[j+1],L[j]
print("List in ascending order=",L)
L=eval(input("Enter the list of numbers"))
Bsort(L)
OUTPUT
Enter the list of numbers[20,17,55,10,60,30,12]
List in ascending order= [10, 12, 17, 20, 30, 55, 60]
30 (ii.) -Write a function Isort(L) where L is the list of
integers passed as arguments. Arrange the data in
ascending order using insertion sort.
def Isort(L):
for i in range(1,len(L)):
j=i-1
t=L[i]
while t<L[j] and j>=0:
L[j+1]=L[j]
j=j-1
L[j+1]=t
print("List in ascending order =",L)
L=eval(input("Enter the list of numbers"))
Isort(L)
OUTPUT
Enter the list of numbers[90,45,67,1,11,100,35]
List in ascending order = [1, 11, 35, 45, 67, 90, 100]
30
STACk OPERATIONS
31-Write a function in python Push(), Pop(), Display()
to add , delete and display the names of students from
the list of description considering them to act as push
and pop operations of the stack data structure.
def Push(Name):
x=input("Enter the name of student ")
Name.append(x)
def Pop(Name):
if Name==[]:
print("Underflow")
else:
print("Name removed",Name.pop())
def Display(Name):
if Name==[]:
print("Underflow")
else:
for i in range(len(Name)-1,-1,-1):
print(Name[i])
L=[]
while True:
print("1 Push Name")
print("2 Pop Name")
print("3 Display Name")
print("4 Exit")
ch=int(input("Enter your choice (1-4) "))
if ch==1:
Push(L)
elif ch==2:
Pop(L)
elif ch==3:
Display(L)
elif ch==4:
print("End of stack operation")
break
else:
print("Invalid choice")
31
OUTPUT
1 Push Name
2 Pop Name
3 Display Name
4 Exit
Enter your choice (1-4) 1
Enter the name of student Riya
1 Push Name
2 Pop Name
3 Display Name
4 Exit
Enter your choice (1-4) 1
Enter the name of student Sam
1 Push Name
2 Pop Name
3 Display Name
4 Exit
Enter your choice (1-4) 2
Name removed Sam
1 Push Name
2 Pop Name
3 Display Name
4 Exit
Enter your choice (1-4) 3
Riya
1 Push Name
2 Pop Name
3 Display Name
4 Exit
Enter your choice (1-4) 4
End of stack operation

32
qUEUE OPERATIONS
32 -Write a function Add(Item), Remove(Item) and
Display(Item) to add, delete and display the items from the list.
The structure of the queue consists of itemno, itemName and
Qty.
def Add(ItemName):
IN=int(input("Enter the item number "))
N=input("Enter the item name ")
Q=int(input("Enter the quantity "))
ItemName.append([IN,N,Q])
def Remove(ItemName):
if ItemName==[]:
print("Underflow")
else:
print("Item details removed",ItemName.pop(0))
def Display(ItemName):
if ItemName==[]:
print("Underflow")
else:
for i in range(0,len(ItemName)):
for j in range(0,len(ItemName[i])):
print(ItemName[i][j])
L=[]
while True:
print("1 Add item details")
print("2 Remove item details")
print("3 Display item details")
print("4 Exit")
ch=int(input("Enter your choice (1-4) "))
if ch==1:
Add(L)
elif ch==2:
Remove(L)
elif ch==3:
Display(L)
elif ch==4:
print("End of queue operation")
break

33
else:
print("Invalid choice")
OUTPUT
1 Add item details
2 Remove item details
3 Display item details
4 Exit
Enter your choice (1-4) 1
Enter the item number 101
Enter the item name Pen
Enter the quantity 4
1 Add item details
2 Remove item details
3 Display item details
4 Exit
Enter your choice (1-4) 1
Enter the item number 102
Enter the item name Pencil
Enter the quantity 5
1 Add item details
2 Remove item details
3 Display item details
4 Exit
Enter your choice (1-4) 2
Item details removed [101, 'Pen', 4]
1 Add item details
2 Remove item details
3 Display item details
4 Exit
Enter your choice (1-4) 3
102
Pencil
5
1 Add item details
2 Remove item details
3 Display item details
4 Exit
Enter your choice (1-4) 4
End of queue operation

34
DATABASES
33- INTRODUCTION TO MYSqL

MySQL was created by a Swedish company, MySQL AB, founded


by Swedes David Axmark, Allan Larsson and Finland Swede Michael
"Monty" Widenius. Original development of MySQL by Widenius and
Axmark began in 1994. The first version of MySQL appeared on 23
May 1995. It was initially created for personal usage
from mSQL based on the low-level language ISAM, which the creators
considered too slow and inflexible. They created a new SQL interface,
while keeping the same API as mSQL. By keeping the API consistent
with the mSQL system, many developers were able to use MySQL
instead of the (proprietarily licensed) mSQL antecedent.

MySQL is written in C and C++. Its SQL parser is written in yacc, but it
uses a home-brewed lexical analyzer. MySQL works on many system
platforms,including AIX, BSDi, FreeBSD, HPUX, ArcaOS, eComStation,
IBM i, IRIX, Linux, macOS, Microsoft Windows, NetBSD, Novell
NetWare, OpenBSD, OpenSolaris, OS/2 Warp, QNX, Oracle
Solaris, Symbian, SunOS, SCO OpenServer, SCO UnixWare, Sanos
and Tru64. A port of MySQL to OpenVMS also exists.[17]
The MySQL server software itself and the client libraries use dual-
licensing distribution. They are offered under GPL version 2, or a
proprietary license.

Support can be obtained from the official manual. Free support


additionally is available in different IRC channels and forums. Oracle
offers paid support via its MySQL Enterprise products. They differ in
the scope of services and in price. Additionally, a number of third
party organisations exist to provide support and services.
MySQL has received positive reviews, and reviewers noticed it
"performs extremely well in the average case" and that the
35
"developer interfaces are there, and the documentation (not to
mention feedback in the real world via Web sites and the like) is very,
very good". It has also been tested to be a "fast, stable and true multi-
user, multi-threaded SQL database server".

MySQL is free and open-source software under the terms of the GNU
General Public License, and is also available under a variety
of proprietary licenses. MySQL was owned and sponsored by
the Swedish company MySQL AB, which was bought by Sun
Microsystems (now Oracle Corporation). In 2010, when Oracle
acquired Sun, Widenius forked the open-source MySQL project to
create MariaDB.

MySQL has stand-alone clients that allow users to interact directly


with a MySQL database using SQL, but more often, MySQL is used
with other programs to implement applications that need relational
database capability. MySQL is a component of the LAMP web
application software stack (and others), which is an acronym
for Linux, Apache, MySQL, Perl/PHP/Python. MySQL is used by many
database-driven web applications, including Drupal, Joomla, phpBB,
and WordPress.

MySQL is an open-source relational database management


system (RDBMS). Its name is a combination of "My", the name of co-
founder Michael Widenius's daughter My, and "SQL", the
abbreviation for Structured Query Language. A relational
database organizes data into one or more data tables in which data
may be related to each other; these relations help structure the data.
SQL is a language programmers use to create, modify and extract
data from the relational database, as well as control user access to
the database.

36
MYSqL qUERIES
34- TABLE CREATION AND qUERIES
Creating and accessing a database:

Creating table:

Inserting data into table:

37
Selecting all columns:

Viewing structure of table:

Selecting specific rows – where clause

Sorting results – order by clause

38
Adding different constraints:

1. Unique constraint

2. Primary key contraint

3. Foreign key constraint

39
4. Default constraint

Modifying data with update command:

Deleting data with delete command:

40
Alter table command:

1. To add a column

2. To redefine a column datatype

41
3. To redefine a column null constraint

4. To rename a column

42
5. To remove a column

Grouping result – group by:

43
Joins:
1. Cartesian product

44
2. Equi-join

Aggregate functions:

1. Avg()

45
2. Count()

3. Max()

4. Sum()

46
INTERFACE PYTHON wITH MYSqL
35 - Write a python database connectivity script that –

(i). Insert records in the table


import mysql.connector as mc
mycon = mc.connect(host="localhost", user="root", passwd="2002",
database="students")
if not mycon.is_connected():
print("My sql is not connected")
else:
cur = mycon.cursor()
cur.execute("insert into data values(106,'Tushi',12,'B')")
mycon.commit()
mycon.close()

OUTPUT

47
(ii). Display records of the table
import mysql.connector as mc
mycon = mc.connect(host="localhost", user="root", passwd="2002",
database="students")
if not mycon.is_connected():
print("My sql is not connected")
else:
cur = mycon.cursor()
cur.execute("select * from Data where Name like 'Yuvi' ")
rec = cur.fetchone()
for i in rec:
print(i)
mycon.close()

OUTPUT

iii). Delete record from the table

import mysql.connector as mc
mycon = mc.connect(host="localhost", user="root", passwd="2002",
database="students")
if not mycon.is_connected():
print("My sql is not connected")
else:
cur = mycon.cursor()
cur.execute("delete from data where grade<'B'")
mycon.commit()
48
cur.execute("select*from data")
rec = cur.fetchall()
for i in rec:
print(i)
mycon.close()

OUTPUT

(iv). Modify record in the table

import mysql.connector as mc
mycon = mc.connect(host="localhost", user="root", passwd="2002",
database="students")
if not mycon.is_connected():
print("My sql is not connected")
else:
cur = mycon.cursor()
cur.execute("update data set grade='A' where name like'Amar'")
mycon.commit()
cur.execute("select*from data")
49
rec = cur.fetchall()
for i in rec:
print(i)
mycon.close()

OUTPUT

50

You might also like