XII-E Practical File 23-24

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 57

Ex.No.1. Program to Calculate Factorial of a number using function.

Aim:
To write a Python program to calculate factorial of a number using function.
Algorithm:
1. Start.
2. Get input number from the user.
3. Call user defined function by passing the number as an argument.
4. Calculate factorial of the passed argument and return the value.
5. Print the result.
6. Stop.

# Program to find factorial of a number


def factorial(n):
f=1
for i in range(1,n+1):
f=f*i
return f
n=int(input("Input a number to compute the factorial : "))
print("Factorial of ",n, " is: ", factorial(n))

Sample Output:
Input a number to compute the factorial: 5
Factorial of 5 is: 120

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.2. Program to find the number of upper case and lower case letters
in a string.

Aim:
To write a Python program to find the number of upper case and lower
case letters in a string which is passed as an argument to the function.

Algorithm:
1. Start.
2. Read string input from the user.
3. Call the user defined function by passing string as an argument.
4. Find the number of upper case letters and lower case letters using
built in functions.
5. Print the result
6. Stop.

#Program to count upper and lower case letters


def string_test(s):
up=0
low=0 for c in s:
if c.isupper():
up+=1
if c.islower():
low+=1
print ("Original String : ", s)
print ("No. of Upper case characters : ", up)
print ("No. of Lower case Characters : ", low)
string=input("Enter any String:")
string_test(string)
Sample Output:

Enter any String: ND Salem


Original String: ND Salem
No. of Upper case characters: 3 No.
of Lower case Characters: 4

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.3. Program to check if a Number is a Prime or not using function.

Aim:
To write a Python program to check if a Number is a Prime or not using
function.

Algorithm:
1. Start
2. Read the number from the user and pass it to the function.
3. Call the function to check whether the entered number is prime or not.
4. If the number is prime function returns True otherwise False.
5. Print the result.
6. Stop.

#Program to check whether the given number is prime or not.


def test_prime(n):
if (n==1):
return False
elif (n==2):
return True
else:
for x in range(2,n):
if(n % x==0):
return False
return True
n=int(input("Enter any integer number:"))
if test_prime(n):
print("Entered Number is Prime")
else:
print("Entered Number is not prime")
Sample Output:

Enter any integer number: 6


Entered Number is not Prime.
Enter any integer number: 7
Entered Number is Prime

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.4. Program to find the occurrence of any word in a string.

Aim:
To write a Python program to find the occurrence of any word in a
string which is passed as an argument to function.

Algorithm:
1. Start
2. Read input string from the user.
3. Read the word to be searched in the above string.
4. Call user defined function by passing string and the word as an argument.
5. Split the passed string and count number of words.
6. Return the count value.
7. Print the result.
8. Stop.

#Program to count any word in a string.


def countWord(str1,word):
s = str1.split()
count=0
for w in s:
if w==word:
count+=1
return count

str1 = input("Enter any sentence :")


word = input("Enter word to search in sentence :")
count = countWord(str1,word)
if count==0:
print("Sorry! ",word," not present ")
else:
print(word," occurs ",count," times")
Sample Output:

Enter any sentence: Meena likes cake and Tina likes chocolate.

Enter word to search in sentence: likes


likes occurs 2 times
Enter any sentence: Meena likes cake and Tina likes chocolates.
Enter word to search in sentence: Likes
Sorry! Likes not present

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.5. Program to generate random number between 1 – 6 to simulate the
dice.

Aim:
To write a Python program to simulate the dice using random module.

Algorithm:

1. Start.
2. Repeatedly generate random number using randint(1,6) and
display the number with equal time interval.
3. Press CTRL+C to stop generating random number.
4. Print the number.
5. Stop.

#Program to simulate the dice

import random
import time
print("Press CTRL+C to stop the dice!!!") play='y'
while play=='y':
try:
while True:
for i in range(10):
print()
n = random.randint(1,6)
print(n)
time.sleep(0.5)
except KeyboardInterrupt:
print("\nYour Number is :",n)
ans=input("Play More? (Y) :")
if ans.lower()!='y':
play='n'
break
Sample Output:
Press CTRL+C to stop the
dice!!! 5
3
6
2
2
3
3
4
5
3
Your Number is: 3
Play More? (Y): n

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.6. Program to print Floyd's triangle.

Aim:
To write a Python Program to print Floyd’s Triangle.

Algorithm:
1. Start.
2. Using Nested For Loop we print the Triangle.
3. Stop.

#Floyd's triangle
n=int(input("Enter the number :"))
for i in range(n,0,-1):
for j in range(n,i-1,-1):
print (j,end=' ')
print('\n')

Sample Output: Enter


the number: 6
6
65
654
6543
65432
654321

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.7. Program to count number of lines and words in a text file.
Aim:
To write a Python program to count the number of lines and words in a text
file.

Algorithm:
1. Start.
2. Create text file using notepad and save it.
3. Open the created text file in read mode.
4. Apply readlines() to read all the lines and count the number of lines.
5. Now set the file pointer to the beginning of file and read the entire file
and count the number of words using split().
6. Print the result
7. Stop.

#Program to count number of lines and words in a text file


myfile=open("Poem.txt","r")
Lines=myfile.readlines()
NOL=len(Lines) myfile.seek(0)
words=myfile.read()
NOW=words.split()
print("Number of Lines in a text file:",NOL)
print("Number of Words in a text file:",len(NOW))

Sample Output:
Number of Lines in a text file: 4
Number of Words in a text file: 23

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.8. Program to count number of vowels and consonants in a text file.

Aim:
To write a Python program to count number of vowels and consonants in a
text file.

Algorithm:
1. Start.
2. Create text file using notepad and save it.
3. Open the created text file in read mode.
4. Read each character from the text file and check whether it is vowel
or consonant.
5. Update the counter variable.
6. Print the result
7. Stop.

# Program to count number of vowels and consonants in a text file.

myfile=open("F:\\TextFile\\Poem.txt","r")
vowels="aeiouAEIOU"
count1=0 count2=0
data=myfile.read()
for i in data:
if i in vowels:
count1=count1+1
else:
count2=count2+1
print("Number of Vowels:",count1)
print("Number of Consonants:",count2)
Sample Output:
Number of Vowels: 38 Number
of Consonants: 78

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.9. Program to copy the content of text file.

Aim:
To write a Python program to copy the content of text file which are starting
with ‘I’ to another file.

Algorithm:
1. Start.
2. Create Source text file using notepad and save it.
3. Open source file in read mode and target file in write mode.
4. Read each line from the source text file and check whether it is
starting with ‘I’.
4. Write the line into target file.
5. Print the content of target file.
6. Stop.

# Program to copy the content of text file to another file.

f=open("F:\\textfile\\poem.txt",'r')
f1=open("CopyPoem.txt","w")
while True:
txt=f.readline()
if len(txt)==0:
break
if txt[0]=='I':
f1.write(txt)
print("File Copied!")
print("Contents of new file:")
f.close()

with open("CopyPoem.txt","r") as f1:


print(f1.read())
Sample Output:
File Copied! Contents
of new file:
I love thee, O my India

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.10. Program to read a text file line by line and display each word
separated by '#'.
AIM:

To write a Python Program to Read a text file "India.txt" line by line


and display each word separated by '#'.
Algorithm:
1. Start.
2. Import pickle module and open binary file in write mode.
3. Get student details from the user and store it in dictionary variable.
4. Write the record into the file using dump().
5. Open the same file in read mode and read its content using load()
6. Display the content of file.
7. Stop.

#Program

f=open('India.txt', 'r')
contents=f.readlines()
for line in contents:
words=line.split()
for i in words:
print(i+'#', end='')
f.close()

Sample Output:

india#is#my#country#all#indians#are#my#brothers#and#sisters#i#love#my#coun
try#

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.11. Program to create binary file.
Aim:
To write a Python program to create binary file and store the details of
a student.

Algorithm:
1. Start.
2. Import pickle module and open binary file in write mode.
3. Get student details from the user and store it in dictionary variable.
4. Write the record into the file using dump().
5. Open the same file in read mode and read its content using load()
6. Display the content of file.
7. Stop.

# Program to create binary file and store the student details.

import pickle stu={}


myfile=open('student.dat','wb')
choice='y'
while choice=='y':
Rno=int(input("Enter Roll Number:"))
Name=input("Enter Name:")
Class=int(input("Enter Class(11/12):"))
Total=int(input("Enter Total Marks:"))
stu['RollNo']=Rno
stu['Name']=Name
stu['Class']=Class
stu['Marks']=Total
pickle.dump(stu,myfile)
choice=input("Do you want to add more records?(y/n)...")
myfile.close()
stu={}
fin=open('student.dat','rb')
try:
print("File Contents:")
while True:
stu=pickle.load(fin)
print(stu)
except EOFError:
fin.close()

Sample Output:

Enter Roll Number: 101


Enter Name:Rajiv
Enter Class(11/12):12 Enter
Total Marks:450
Do you want to add more records?
(y/n)...y
Enter Roll Number: 102
Enter Name:Sanjay
Enter Class(11/12):12 Enter
Total Marks: 400
Do you want to add more records? (y/n)...n File
Contents:
{'RollNo': 101, 'Name': 'Rajiv', 'Class': 12, 'Marks': 450}
{'RollNo': 102, 'Name': 'Sanjay', 'Class': 12, 'Marks': 400}

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.12. Program to update the content of binary file.

Aim:
To write a Python program to update the content of binary file.
Algorithm:
1. Start.
2. Import pickle module and open binary file in read/write mode.
3. Get the roll number of a student to identify the record.
4. Read the file using load() and identify the record to be updated.
5. Update the mark of a student and write the updated record back into the
file using dump().
6. Now display the content of updated file.
7. Stop.

# Program to update the records of the binary file.

import pickle
stu={}
found=False
myfile=open('student.dat','rb+')
n=int(input("Enter Roll number of a student to update his mark:"))
try:
while True:
pos=myfile.tell()
stu=pickle.load(myfile)
if stu['RollNo']==n:
stu['Marks']+=10
myfile.seek(pos)
pickle.dump(stu,myfile)
found=True
except EOFError:
if found==False:
print("No matching record found!")
else:
print("Record Successfully Updated!")
try:
myfile.seek(0)
print("File Content after updation:")
while True:
stu=pickle.load(myfile)
print(stu)
except EOFError:
myfile.close()
myfile.close()

Sample Output:

Enter Roll number of a student to update his mark: 101


Record Successfully Updated!
File Content after updation:
{'RollNo': 101, 'Name': 'Rajiv', 'Class': 12, 'Marks': 460}
{'RollNo': 102, 'Name': 'Sanjay', 'Class': 12, 'Marks': 400}
Sample Output 2:
Enter Roll number of a student to update his mark: 103
No matching record found!

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.13. Program to create CSV file.

Aim:

To write a Python program to create csv file to store information about


some products.

Algorithm:

1. Start.
2. Import csv module and open file in write mode.
3. Create writer object and write the product details into the file using
writerow().
4. Open the above created file in read mode using with statement.
5. Read the file using reader object.
6. Display the contents of file.
7. Stop.

# Program to create a CSV file to store product details.

import csv myfile=open('Product.csv','w',newline='')


prod_writer=csv.writer(myfile)
prod_writer.writerow(['CODE','NAME','PRICE'])
for i in range(2):
print("Product", i+1)
code=int(input("Enter Product code:"))
name=input("Enter Product Name:")
price=float(input("Enter Price:"))
prod=[code,name,price]
prod_writer.writerow(prod)
print("File created successfully!")
print("File Contents:")
print(“
myfile.close()
with open("Product.csv","r",newline='\n') as fh:
prod_reader=csv.reader(fh)
for rec in prod_reader:
print(rec)

Sample Output:
Product 1
Enter Product code: 104
Enter Product Name: Pen
Enter Price:200
Product 2
Enter Product code: 405 Enter
Product Name: Marker Enter
Price: 50
File created
successfully! File
Contents:
-----------------------
['CODE', 'NAME', 'PRICE']
['104', 'Pen', '200.0']
['405', 'Marker', '50.0']

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.14. Program to create Stack.

Aim:
To write a Python program to create Stack using an element.

Algorithm:

1. Start
2. To push an item in the stack, use the list function append list.append(item)
3. To pop an item in the stack, use the list function pop list.pop()
4. To get the top most item in the stack, write list[-1]
5. Display the content of the Stack.
6. Stop.

# Program to create a Stack using Student details.

def check_stack_isEmpty(stk):
if stk==[]:
return True
else:
return False

def push(stk,e):
stk.append(e)
top = len(stk)-1

def display(stk):
if check_stack_isEmpty(stk):
print("Stack is Empty")
else:
top = len(stk)-1
print(stk[top],"-Top")
for i in range(top-1,-1,-1):
print(stk[i])
def pop_stack(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
e = stk.pop()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e

def peek(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]

s=[] # An empty list to store stack elements, initially its empty top = None
# This is top pointer for push and pop operation.
def main_menu():
while True:
print("Stack Implementation")
print("1 - Push")
print("2 - Pop")
print("3 - Peek")
print("4 - Display")
print("5 - Exit")
ch = int(input("Enter the your choice:"))
if ch==1:
el = int(input("Enter the value to push an element:"))
push(s,el)
elif ch==2:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("Element popped:",e)
elif ch==3:
e=peek(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("The element on top is:",e)
elif ch==4:
display(s)
elif ch==5:
break
else:
print("Sorry, You have entered invalid option")
main_menu()

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Output
Ex.No.15. Program to create Stack using Employee details. Aim:

To write a Python program to create Stack using Employee Details.

Algorithm:

1. Start
2. To push an item in the stack, use the list function append list.append(item)
3. To pop an item in the stack, use the list function pop list.pop()
4. To get the top most item in the stack, write list[-1]
5. Display the content of the Stack.
6. Stop.

# Program to create a Stack using Employee details using (empno, name).


stk=[]
top=-1
def line():
print('~'*100)
def isEmpty():
global stk
if stk==[]:
print("Stack is empty!!!")
else:
None
def push():
global stk
global top
empno=int(input("Enter the employee number to push:"))
ename=input("Enter the employee name to push:")
stk.append([empno,ename])
top=len(stk)-1
def display():
global stk
global top
if top==-1:
isEmpty()
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[i])
def pop_ele():
global stk
global top
if top==-1:
isEmpty()
else:
stk.pop()
top=top-1

def main():
while True:
line()
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
ch=int(input("Enter your choice:"))
if ch==1:
push()
print("Element Pushed")
elif ch==2:
pop_ele()
elif ch==3:
display()
else:
print("Invalid Choice")
break
main()
Output

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Part B
EX.No.16
5 sets of SQL queries using one/two tables.

In this section Practical file computer science class 12, 5 sets of SQL queries are
required. These queries can be performed either on one or two tables. So here
we go!

Queries Set 1 (Database Fetching records)


[1] Consider the following MOVIE table and write the SQL queries based on it.

Movie Movie Release Production Business


Type
ID Name Date Cost Cost
The Kashmir
M001 Files Action 2022/01/26 1245000 1300000
M002 Attack Action 2023/01/28 1120000 1250000
M003 Looop Lapeta Thriller 2023/02/01 250000 300000
M004 Badhai Do Drama 2023/02/04 720000 68000
Shabaas h
M005 Mithu Biography 2023/02/04 1000000 800000
M006 Gehraiyaan Romance 2023/02/11 150000 120000

1. Display all information from movie.


2. Display the type of movies.
3. Display movieid, moviename, total_eraning by showing the business doneby
the movies. Claculate the business done by movie using the sum of
productioncost and businesscost.
4. Display movieid, moviename and productioncost for all movies
with productioncost greater thatn 150000 and less than 1000000.
5. Display the movie of type action and romance.
6. Display the list of movies which are going to release in February, 2023.
ANSWERS
Output:

[1] Select * from movie;

2. Select distinct(type) from movie;


3. Select movieid, moviename, productioncost + businesscost
“total earning” from movie;

4. select movie_id,moviename, productioncost from movie where producst >150000


and productioncost<1000000;

5. Select moviename from movie where type =’action’ or type=’romance’;


6. Select moviename from moview where month(releasedate)=2;
Queries
Set 2 (Based on Functions)

1. Write a query to display cube of 5.


2. Write a query to display the number 563.854741 rounding off to the
next hundred.
3. Write a query to display “put” from the word “Computer”.
4. Write a query to display today’s date into DD.MM.YYYY format.
5. Write a query to display ‘DIA’ from the word “MEDIA”.
6. Write a query to display moviename – type from the table movie.
7. Write a query to display first four digits of productioncost.
8. Write a query to display last four digits of businesscost.
9. Write a query to display weekday of release dates.
10. Write a query to display dayname on which movies are going to be
released.

Answers:

[1] Select pow (5, 3);


[2] Select round (563.854741,-2);

[3] Select mid(“Computer”,4,3);

[4] select
concat(day(now()),concat(‘.’,month(now()),concat(‘.’,year(now()))))
“Date”;
[5] Select right(“Media”,3);

[6] Select concat(moviename,concat(‘ – ‘,type)) from movie;


[7] Select left(productioncost,4) from movie;

[8] Select right(businesscost,4) from movie;

[9] Select weekday(releasedate) from movie;


[10] Select dayname(releasedate) from movie;
Queries
Set 3 (DDL Commands)

Suppose your school management has decided to conduct cricket matches


between students of Class XI and Class XII. Students of each class are asked
to join any one of the four teams – Team Titan, Team Rockers, Team Magnet
and Team Hurricane. During summer vacations, various matches will be
conducted between these teams. Help your sports teacher to do the following:
1. Create a database “Sports”.
2. Create a table “TEAM” with following considerations:
● It should have a column TeamID for storing an integer value between 1
to 9, which refers to unique identification of a team.
● Each TeamID should have its associated name (TeamName), which
should be a string of length not less than 10 characters.
● Using table level constraint, make TeamID as the primary key.

● Show the structure of the table TEAM using a SQL statement.

● As per the preferences of the students four teams were formed as


given below. Insert these four rows in TEAM table:

● Row 1: (1, Tehlka)


● Row 2: (2, Toofan)
● Row 3: (3, Aandhi)
● Row 3: (4, Shailab)
Show the contents of the table TEAM using a DML statement.
3. Now create another table MATCH_DETAILS and insert data as shown
below. Choose appropriate data types and constraints for each attribute.
First Second
Match First Second
MatchID Team Team
Date TeamID TeamID
Score
Score
M1 2021/12/20 1 2 107 93
M2 2021/12/21 3 4 156 158
M3 2021/12/22 1 3 86 81
M4 2021/12/23 2 4 65 67
M5 2021/12/24 1 4 52 88
M6 2021/12/25 2 3 97 68

ANSWERS
[1] Create database sports.
[2] Creating table with the given specification.
create table team
-> (teamid int(1),
-> teamname varchar(10), primary key(teamid));
Showing the structure of table using SQL statement:
desc team;
Inserting data:
mqsql> insert into team values(1,'Tehlka');

Show the content of table – team:


select * from team;
Creating another table:
create table match_details
-> (matchid varchar(2) primary key,
-> matchdate date,
-> firstteamid int(1) references team(teamid),
-> secondteamid int(1) references team(teamid),
-> firstteamscore int(3),
-> secondteamscore int(3));
Queries
Set 4 (Based on Two Tables)

1. Display the matchid, teamid, teamscore whoscored more than 70


in first ining along with team name.
2. Display matchid, teamname and secondteamscore between 100 to 160.
3. Display matchid, teamnames along with matchdates.
4. Display unique team names
5. Display matchid and matchdate played by Anadhi and Shailab.

Answers:

[1] select match_details.matchid, match_details.firstteamid,


team.teamname,match_details.firstteamscore from match_details, team
where match_details.firstteamid = team.teamid and
match_details.firstteamscore>70;
[2] select matchid, teamname, secondteamscore from match_details,
team where match_details.secondteamid = team.teamid and
match_details.secondteamscore between 100 and 160;

[3] select matchid, teamname, firstteamid, secondteamid,matchdate


from match_details, team where
match_details.firstteamid = team.teamid;
[4] select distinct(teamname) from match_details, team
where match_details.firstteamid = team.teamid;

[5] select matchid,matchdate from match_details, team


where match_details.firstteamid = team.teamid and
team.teamname in (‘Aandhi’,’Shailab’);
Queries
Set 5 (Group by, Order By)

Consider the following table STOCK table to answer the queries:


ITEMNO ITEM DCODE QTY UNITPRICE STOCKDATE

S005 Ballpen 102 100 10 2018/04/22


S003 Gel Pen 101 150 15 2018/03/18
S002 Pencil 102 125 5 2018/02/25
S006 Eraser 101 200 3 2018/01/12

S001 Sharpner 103 210 5 2018/06/11


S004 Compass 102 60 35 2018/05/10
S009 A4 Papers 102 160 5 2018/07/17

1. Display all the items in the ascending order of stockdate.


2. Display maximum price of items for each dealer individually
as per dcode from stock.
3. Display all the items in descending orders of itemnames.
4. Display average price of items for each dealer individually as
per doce from stock which avergae price is more than 5.
5. Display the sum of quantity for each dcode.
[1] select * from stock order by stockdate;

[2] select dcode, max(unitprice) from stock group by dcode;

[3] select * from stock order by item desc;


[4] select dcode,avg(unitprice) from stock group by dcode having
avg(unitprice)>5;

[5] select dcode, sum(qty) from stock group by dcode;


PYTHON-MYSQL CONNECTIVITY PROGRAMS

Ex.No.17. Program to fetch all the records from Student Table. Aim:

To write a Python program to fetch all the records from the Student Table.

Algorithm:

1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Fetch all the records from the table using fetchall().
6. Traverse the result set using for loop and print the records.
7. Close the connection using close().
8. Stop.

Program:

# Program to fetch all the records from Student table import


mysql.connector as sqltor
con=sqltor.connect(host="localhost",user="root",passwd="mysql1233",d
atabase="NDHCS")
if con.is_connected==False:
print('Error')
cursor=con.cursor()
cursor.execute("select * from Student")
data=cursor.fetchall()
count=cursor.rowcount
print("No.Rows:",count)
for row in data:
print(row)
con.close()
Sample Output:
Ex.No.18. Program to fetch records from Student Table.

Aim:

To write a Python program to fetch the records from the Student


Table which satisfies the given condition.

Algorithm:

1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Execute SQL query with string formatting.
6. Fetch all the records from the table using fetchall().
7. Traverse the result set using for loop and print the records.
8. Close the connection using close().
9. Stop.

Program:

# Program to fetch records which satisfies the given condition.


import mysql.connector as sqltor
con=sqltor.connect(host="localhost",user="root",passwd="mysql123",datab
ase="NDHCS")
if con.is_connected==False:
print('Error')
cur=con.cursor()
cur.execute("select * from student where percentage>={}".format(80))
data=cur.fetchall()
count=cur.rowcount
print("No.Rows:",count)
for row in data:
print(row)
con.close()

Sample Output:
Ex: No.19. Program to insert records into Table.

Aim:

To write a Python program to insert new record into Student Table.

Algorithm:

1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Execute insert command with string formatting and apply commit() to
save the changes permanently.
6. Execute select query and fetch all the records using fetchall().
7. Traverse the result set using for loop and print the records.
8. Close the connection using close().
9. Stop.

Program:
# Program to insert new record into table.

import mysql.connector as sqltor


con=sqltor.connect(host="localhost",user="root",passwd="mysql123",datab
ase="NDHCS")
if con.is_connected==False:
print('Error')
cur=con.cursor()
query="insert into student values({},'{}',{},'{}',{},{})".
format(106,'Raj',12,'A',430,86)
cur.execute(query)
con.commit()
print("Record Inserted")
cur.execute("Select * from Student")
print("Table after insertion")
data=cur.fetchall()
for row in data:
print(row)
con.close()

Sample Output:
Ex.No.20. Program to update records in a table.

Aim:

To write a Python program to update record in a table.

Algorithm:

1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Execute insert command with string formatting and apply commit() to
save the changes permanently.
6. Execute select query and fetch all the records using fetchall().
7. Traverse the result set using for loop and print the records.
8. Close the connection using close().
9. Stop.

Program:

# Program to update record in


a table import mysql.connector
as sqltor
con=sqltor.connect(host="localhost",user="root",passwd="mysql123",datab
ase="NDHCS")
if con.is_connected==False:
print('Error')
cur=con.cursor()
query="update student set section='{}' where
name='{}'".format('B','Neha')
cur.execute(query)
con.commit() print("Record Updated")
cur.execute("Select * from Student")
print("Table after Updation")
data=cur.fetchall()
for row in data:
print(row)
con.close()

Sample Output:

You might also like