0% found this document useful (0 votes)
37 views41 pages

Practical file Computer Science Class 12th 2024-25-output

Computer science project

Uploaded by

tousifkarim602
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)
37 views41 pages

Practical file Computer Science Class 12th 2024-25-output

Computer science project

Uploaded by

tousifkarim602
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/ 41

GBSSS, Jasola Village Delhi 110025

PRACTICAL FILE

th

SCHOOL
LOGO
SCHOOL NAME AND ADDRESS
STUDENT’S DETAIL
Roll No.: [Roll Number]
Name of Student: [Student Name]
Class: Computer Science
Subject: Computer Science (083)
School: [School Name] Submitted by;:

Class and Section:


Roll No:
CERTIFICATE

This is to certify that , a student of Class 12,


Section - has successfully completed and submitted the
practical file of Computer Science
(083) as per the guidelines provided by CBSE in the prescribed
curriculum for academic year 2024-25 for accomplishment of
Senior School Certificate Examination - 2025.
The practical file has been evaluated and found correct in
accordance with the guidelines provided by the board- for
Academic year 2024-25. The work has been completed and
presented in a satisfactory manner.
No. of practicals certified are:19

Internal Examiner External Examiner

Principal
CLASS XII
COMPUTER SCIENCE PRACTICAL FILE FOR SESSION 2024-25
INDEX
Date of
Sr. No. Name of the Experiment Experiment Remarks

1 Exp. Aim Date Sign No 1 Program to read and display file content line by
line with each word separated by “ #”

2 Program to read the content of file and display the totalnumber of


consonants, uppercase, vowels and lowercase characters.

3 Program to read the content of file line by line and write it to another file
except for the lines contains “a” letter in it.
Program to store students’ details like admission number, roll number,
4 name and percentage in a dictionary and display information on the
basis of admission number.

5 Program to create binary file to store Roll no and Name, Search any Roll
no and display name if Roll no found otherwise “Roll no not found”

6 Program to create binary file to store Roll no, Name and Marks and
update marks of entered Roll no.
7 Program to generate random number 1-6, simulating a dice.
8
Program to implement Stack in Python using List.

9 Create a CSV file by entering user-id and password, read and search the
password for given user- id.

10 To write SQL-Queries for the following Questions based on the given


table

11 To write SQL-Queries for the following Questions based on the given


table

12 To write SQL Queries for the following Questions based on the given two
table

13 Database query using SQL (Mathematical, string, Date and time


functions in SQL

14 Database query using SQL (Aggregate functions ,Group by ,order by


query in SQL)
15 Write a Program to show MySQL database connectivity in python.

16 Program to connect with database and store record of employee and


display records.
Program to connect with database and search employee number in table
17 employee and display record, if empno not found display appropriate
message

18 Perform all the operations (Insert, Update, Delete, Display) with reference
to table ‘students’ through MySQL-Python connectivity
Write a program to connect Python with MySQL using database
19 connectivity and perform the operation on data in database:
Fetch records from the table using fetchall ()

Page 1
#Program to read content of file line by line
#and display each word separated by '#'

f = open("file1.txt")
for line in f:
words=line.split()
for w in words:
print(w+'#',end="")
print()
f.close()

NOTE : if the original content of file is:

India is my countryI lovepython


Python learning is fun

OUTPUT

============= RESTART: D:\Raval\Pr_1.py ============


India#is#my#
countryI#love#python#
Python#learning#is#fun#
>>>
Program 2: Program to read the content of file and display the total number of
consonants, uppercase, vowels and lower case characters.

f = open("file1.txt")
v=0
c=0
u=0
l=0
o=0
data = f.read()
vowels=['a','e','i','o','u']
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
o+=1
print("Total Vowels in file :",v)
print("Total Consonants in file :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
print("Total Other than letters :",o)
f.close()

OUTPUT
============= RESTART: D:\Raval\Pr_2.py =======
Total Vowels in file : 16
Total Consonants in file : 30
Total Capital letters in file : 3
Total Small letters in file : 43
Total Other than letters : 0
>>>
f1 = open("file1.txt")
f2 = open("file2copy.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print("## File Copied Successfully! ##")
f1.close()
f2.close()

NOTE : if the original content of file1 is:

India is my countryI lovepython


Python learning is fun

OUTPUT
============= RESTART: D:\Raval\Pr_3.py =======
## File Copied Successfully! ##
>>>
Program 4:
Program to store student’s details like admission number, roll number, name and percentage in a
dictionary and display information on the basis of admission number.

record = dict ()
i=1
n= int (input ("How many records u want to enter: "))
while(i<=n):
Adm = input("Enter Admission number: ")
roll = input("Enter Roll Number: ")
name = input("Enter Name :")
perc = float(input("Enter Percentage : "))
t = (roll,name, perc)
record[Adm] = t
i=i+1
Nkey = record.keys()
for i in Nkey:
print("\nAdmno- ", i, " :")
r = record[i]
print("Roll No\t", "Name\t", "Percentage\t")
for j in r:
print(j, end = "\t")

OUTPUT
============= RESTART: D:\Raval\Pr_4.py =======
How many records u want to enter: 2
Enter Admission number: 101
Enter Roll Number: 38
Enter Name :Ramesh
Enter Percentage : 78
Enter Admission number: 102
Enter Roll Number: 39
Enter Name :Mahesh
Enter Percentage : 79

Admno- 101 :
Roll No Name Percentage
38 Ramesh 78.0
Admno- 102 :
Roll No Name Percentage
39 Mahesh 79.0
>>>
import pickle
D={}
f=open("Studentdetails.dat","wb")
def write():
while True:
rno = int(input("Enter Roll no : "))
n = input("Enter Name : ")
D['Roll_No']=rno
D['Name'] = n
pickle.dump(D,f)
ch = input("More ? (Y/N)")
if ch in 'Nn':
break
f.close()
def Search() :
found = 0
rollno= int(input("Enter Roll no Whose name you want to display :"))
f = open("Studentdetails.dat", "rb")
try:
while True:
rec = pickle.load(f)
if rec['Roll No']==rollno:
print(rec['Name'])
found = 1
break
except EOFError:
if found == 0:
print("Sorry not Found. .. ")
f.close()
write()
Search()
OUTPUT
============= RESTART: D:\Raval\Pr_5.py =======

Enter Roll no : 1
Enter Name : Ramesh
More ? (Y/N)y
Enter Roll no : 2
Enter Name : Mahesh
More ? (Y/N)y
Enter Roll no Whose name you want todisplay :2
Mahesh
#Program to create a binary file to store Rollno and name
#Search for Rollno and display record if found
#otherwise"Roll no. not found"

import pickle
def Write():
f = open("Studentdetails.dat", 'wb')
while True:
r =int(input ("Enter Roll no : "))
n = input("Enter Name : ")
m = int(input ("Enter Marks : "))
record = [r,n,m]
pickle.dump(record, f)
ch = input("Do you want to enter more ?(Y/N)")
if ch in 'Nn':
break
f.close()
def Read():
f = open("Studentdetails.dat",'rb')
try:
while True:
rec=pickle.load(f)
print(rec)
except EOFError:
f.close()
def Update():
f = open("Studentdetails.dat", 'rb+')
rollno = int(input("Enter roll no whoes marks you want to update"))
try:
while True:
pos=f.tell()
rec = pickle.load(f)
if rec[0]==rollno:
um = int(input("Enter Update Marks:"))
rec[2]=um
f.seek(pos)
pickle.dump(rec,f)
#print(rec)
except EOFError:
f.close()
Write()
Read()
Update()
Read()
OUTPUT
============= RESTART: D:\Raval\Pr_6.py =======

Enter Roll no : 1
Enter Name : ramesh
Enter Marks : 78
Do you want to enter more ?(Y/N)N
[1, 'ramesh', 78]
Enter roll no whoes marks you want to update1
Enter Update Marks:87
[1, 'ramesh', 87]
>>>
# Program to generate random number between 1 -6
# tosimulate the dice

import random
while True:
print("="*55)
print("***********************Roling Dice****************************")
print("="*55)
num = random.randint(1,6)
if num ==6:
print("Hey.....You got",num,". ...... Congratulations!!!!")
elif num ==1:
print("Well tried. ... But you got",num)
else:
print("You got:",num)
ch=input("Roll again? (Y/N)")
if ch in "Nn":
break
print("Thank for playing!!!!!!!!")

OUTPUT
============= RESTART: D:\Raval\Pr_7.py =======
=======================================================
***********************Roling Dice****************************
=======================================================
You got: 2
Roll again? (Y/N)y Thank for
playing!!!!!!!!
=======================================================
***********************Roling Dice****************************
=======================================================
Hey.....You got 6 ......Congratulations!!!!
employee=[]
def push():
empno=input("Enter empno ")
name=input("Enter name ")
sal=input("Enter sal ")
emp=(empno,name,sal)
employee.append(emp)
def pop():
if(employee==[]):
print("Underflow / Employee Stack in empty")
else:
empno,name,sal=employee.pop()
print("poped element is ")
print("empno ",empno," name ",name," salary ",sal)
def traverse():
if not (employee==[]):
n=len(employee)
for i in range(n-1,-1,-1):
print(employee[i])
else:
print("Empty , No employee to display")
while True:
print("1. Push")
print("2. Pop")
print("3. Traversal")
print("4. Exit")
ch=int(input("Enter your choice "))
if(ch==1):
push()
elif(ch==2):
pop()
elif(ch==3):
traverse()
elif(ch==4):
print("End")
break
else:
print("Invalid choice")
OUTPUT
============= RESTART: D:\Raval\Pr_8.py =======

1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 1
Enter empno 101
Enter name Ramesh
Enter sal 34000
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 3
('101', 'Ramesh', '34000')
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice
import csv
with open("user_info.csv", "w") as obj:
fileobj = csv.writer(obj)
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue
with open("user_info.csv", "r") as obj2:
fileobj2 = csv.reader(obj2)
given = input("enter the user id to be searched\n")
for i in fileobj2:
next(fileobj2)
# print(i,given)
if i[0] == given:
print(i[1])
break

OUTPUT
============= RESTART: D:\Raval\Pr_9.py =======

enter id: 101


enter password: 12345
press Y/y to continue and N/n to terminate the program
N
enter the user id to be searched
101
12345
>>>
SQL
queries
Rollno Name Gender Age Dept DOA Fees
1 Arun M 24 COMPUTER 1997-01-10 120
2 Ankit M 21 HISTORY 1998-03-24 200
3 Anu F 20 HINDI 1996-12-12 300
4 Bala M 19 NULL 1999-07-01 400
5 Charan M 18 HINDI 1997-09-05 250
6 Deepa F 19 HISTORY 1997-06-27 300
7 Dinesh M 22 COMPUTER 1997-02-25 210
8 Usha F 23 NULL 1997-07-31 200

(a) Write a Query to Create a new database in the name of "STUDENTS"


Sol:mysql> CREATE DATABASE STUDENTS;

(b) Write a Query to Open the database "STUDENTS"


Sol:mysql> USE STUDENTS;
(c) Write a Query to create the above table called: Info
Sol:
mysql> CREATE TABLE STU(Rollno int Primary key,Name varchar(10),Gender
varchar(3),Age int,Dept varchar(15),DOA date,Fees int);

(d) Write a Query to list all the existing database names.


Sol:
mysql> SHOW DATABASES;

(e) Write a Query to List all the tables that exists in the current database.
Sol:
mysql> SHOW TABLES;
Output:
(f) Write a Query to insert all the rows of above table into Info table.
Sol:
INSERT INTO STU VALUES (1,'Arun','M', 24,'COMPUTER','1997-01-10', 120);INSERT
INTO STU VALUES (2,'Ankit','M', 21,'HISTORY','1998-03-24', 200);
INSERT INTO STU VALUES (3,'Anu','F', 20,'HINDI','1996-12-12', 300);
INSERT INTO STU VALUES (4,'Bala','M', 19, NULL,'1999-07-01', 400);
INSERT INTO STU VALUES (5,'Charan','M', 18,'HINDI','1997-06-27', 250);
INSERT INTO STU VALUES (6,'Deepa','F', 19,'HISTORY','1997-06-27', 300);
INSERT INTO STU VALUES (7,'Dinesh','M', 22,'COMPUTER','1997-02-25', 210);
INSERT INTO STU VALUES (8,'Usha','F', 23, NULL,'1997-07-31', 200);

(g) Write a Query to display all the details of the Employees from the above table 'STU'.

Sol:

mysql> SELECT * FROM STU;

Output:

(h) Write a query to Rollno, Name and Department of the students from STU
table.
Sol:
mysql> SELECT ROLLNO,NAME,DEPT FROM STU;
Program 11: To write SQL- Queries for the following Questions based on the
given table:

Rollno Name Gender Age Dept DOA Fees


1 Arun M 24 COMPUTER 1997-01-10 120
2 Ankit M 21 HISTORY 1998-03-24 200
3 Anu F 20 HINDI 1996-12-12 300
4 Bala M 19 NULL 1999-07-01 400
5 Charan M 18 HINDI 1997-09-05 250
6 Deepa F 19 HISTORY 1997-06-27 300
7 Dinesh M 22 COMPUTER 1997-02-25 210
8 Usha F 23 NULL 1997-07-31 200

(a) Write a Query to delete the details of Roll number is 8.


Sol:

mysql> DELETE FROM STU WHERE ROLLNO=8;

Output (After Deletion):

(b) Write a Query to change the fess of Student to 170 whose Roll number is 1, if the existing
fessis less than 130.
Sol:

mysql> UPDATE STU SET FEES=170 WHERE ROLLNO=1 AND


FEES<130;

Output(After Update):
(c) Write a Query to add a new column Area of type varchar in table STU.

Sol:
mysql> ALTER TABLE STU ADD AREA VARCHAR(20);
Output:

(d) Write a Query to Display Name of all students whose Area Contains NULL.

Sol:
mysql> SELECT NAME FROM STU WHERE AREA IS NULL;

Output:

(e) Write a Query to delete Area Column from the table STU.

Sol:
mysql> ALTER TABLE STU DROP AREA;
Output:

(f) Write a Query to delete table from Database.


Sol:
mysql> DROP TABLE STU;
Output:
TABLE: STOCK
Pno Pname Dcode Qty UnitPrice StockDate
5005 Ball point pen 102 100 10 2021-03-31
5003 Gel pen premium 102 150 15 2021-01-01
5002 Pencil 101 125 4 2021-02-18
5006 Scale 101 200 6 2020-01-01
5001 Eraser 102 210 3 2020-03-19
5004 Sharpner 102 60 5 2020-12-09
5009 Gel pen classic 103 160 8 2022-01-19

TABLE: DEALERS
Dcode Dname
101 Sakthi Stationeries
103 Classic Stationeries
102 Indian Book House

(a) To display the total Unit price of all the products whose Dcode as 102.

Sol:
mysql> SELECT SUM(UNITPRICE) FROM STOCK GROUP BY DCODE
HAVINGDCODE=102;
Output:

(b) To display details of all products in the stock table in descending order of Stock date.

Sol:
mysql> SELECT * FROM STOCK ORDER BY STOCKDATE DESC;

Output:
(c) To display maximum unit price of products for each dealer individually as
per dcodefrom the table Stock.

Sol:

mysql> SELECT DCODE,MAX(UNITPRICE) FROM STOCK


GROUP BY DCODE;
Output:

(d) To display the Pname and Dname from table stock and dealers.

Sol:
mysql> SELECT PNAME,DNAME FROM STOCK S,DEALERS D
WHERE S.DCODE=D.DCODE;

Output:
Practical 13-Aim: Database query using SQL (Mathematical, string,
Date and time functions in SQL)

Consider table SALESMAN with following data:


SNO SNAME SALARY BONUS DATEOFJOIN
A01 Beena Mehta 30000 45.23 2019-10-29
A02 K. L. Sahay 50000 25.34 2018-03-13
B03 Nisha Thakkar 30000 35.00 2017-03-18
B04 Leela Yadav 80000 NULL 2018-12-31
C05 Gautam Gola 20000 NULL 1989-01-23
C06 Trapti Garg 70000 12.37 1987-06-15
D07 Neena Sharma 50000 27.89 1999-03-18

1) Display Salesman name , bonus after rounding off to zero decimal places.
Select SNAME, round(BONUS,0) from SALESMAN;

2) Display name, total salary of all salesman after addition of salary and
bonus and truncate it to 1 decimal places.
Select sname, truncate((SALARY+BONUS),1) from SALESMAN;
3
Page
3) Display remainder of salary and bonus of Salesman whose SNO starting
with ‘A’
Select MOD(SALARY,BONUS) from SALESMAN where SNO like ’A%’;

4) Display position of occurrence of string “ta” in salesmen name.


Select sname, instr(Sname,”ta”) from SALESMAN;

5) Display four characters from salesman name starting from second


character.
Select sname, substr(Sname,2,4) from SALESMAN;

4
Page
6) Display last 5 characters of name of SALESMAN.
Select sname, right(Sname,5) from SALESMAN;

7) Display details of salesman whose name containing 10 characters.


Select * from salesman where length(sname)=10;

8) Display month name for the date of join of salesman


Select DATEOFJOIN, monthname(DATEOFJOIN) from SALESMAN;

9) Display currentdate and day of the year of current date.


Select date (now()),dayofyear(date(now())) from dual;
5
Page
10) Display name of the weekday for the DATEOFJOIN of SALESMAN;
Select DATEOFJOIN,dayname(DATEOFJOIN) from SALESMAN;

11) Display SNO, name of the youngest SALESMAN.


Select sno, sname, dateofjoin from salesman where dateofjoin=(select
max(DATEOFJOIN) from SALESMAN);

12) Display name and salary of the oldest SALESMAN.


Select sname, salary, dateofjoin from salesman where dateofjoin=(select
min(dateofjoin) from salesman);

6
Page
Practical `14-Aim: Database query using SQL (Aggregate functions ,Group
by ,order by query in SQL)

Consider the following table Vehicle:


V_no Type Company Price Qty
AW125 Wagon Maruti 250000 25
J00083 Jeep Mahindra 4000000 15
S9090 SUV Mistubishi 2500000 18
M0892 Mini Van Datsun 1500000 26
W9760 SUV Maruti 2500000 18
R2409 Mini Van Mahindra 350000 15

1. Display the average price of each type of vehicle having quantity more than
20.
Select Type, avg(price) from vehicle where qty>20 group by Type;

2. Count the type of vehicles manufactured by each company.


Select Company, count(distinct Type) from Vehicle group by Company;

7
Page
3. Display total price of all types of vehicle.
Select Type, sum(Price* Qty) from Vehicle group by Type;

4. Display the details of the vehichle having maximum price.


Select * from vehicle where price=(select max(price) from vehicle);

5. Display total vehicles of Maruti company.


Select company,sum(qty) from vehicle
group by company
having company='Maruti';
8
Page
6. Display average price of all type of vehicles.
Select type,avg(price) from vehicle group by type;

7. Display type and minimum price of each vehicle company.


Select type,company,min(price) from vehicle group by company;

8. Display minimum, maximum, total and average price of Mahindra


company vehicles.
Select company, min(price),max(price),sum(price),avg(price) from vehicle where
company='Mahindra';
9
Page
9. Display details of all vehicles in ascending order of their price.
Select * from vehicle order by price asc;

10.Display details of all vehicles in ascending order of type and descending


order of vehicle number.
Select * from vehicle order by type asc,v_no desc;

10
Page
Python
Database
Connectivity
Program 15: Write a Program to show MySQL database
connectivity in python.

Solution: import mysql.connector

con=mysql.connector.connect(host='localhost',user='root',passwor
d='',db='school') stmt=con.cursor()
query='select * from student;'
stmt.execute(query)
data=stmt.fetchone()
print(data)
Program 16: Program to connect with database and store record of employee and display
records.

import mysql.connector as mycon


con = mycon.connect(host='localhost',
user='root',
password="root")
cur = con.cursor()
cur.execute("create database if not exists company")
cur.execute("use company")
cur.execute("create table if not exists employee(empno int, name varchar(20), dept varchar(20),salary int)")
con.commit()
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
choice = int(input("Enter Choice :"))
if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
elif choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()
print("%10s"%"EMPNO","%20s"%"NAME","%15s"%"DEPARTMENT", "%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
elif choice==0:
con.close()
print("## Bye!! ##")
OUTPUT:

1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :101
Enter Name :RAMESH
Enter Department :IT
Enter Salary :34000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :2
EMPNO NAME DEPARTMENT SALARY
101 RAMESH IT 34000
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice : 0
Program 17: Program to connect with database and search employee number in table
employee and display record, if empno not found display appropriate message.

import mysql.connector as mycon


con = mycon.connect(host='localhost',
user='root',
password="root",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO", "%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
ans=input("SEARCH MORE (Y) :")

OUTPUT:
########################################
EMPLOYEE SEARCHING FORM
########################################

ENTER EMPNO TO SEARCH :101


EMPNO NAME DEPARTMENT SALARY
101 RAMESH IT 34000
SEARCH MORE (Y) :
Program 18: Perform all the operations (Insert, Update, Delete, Display) with reference to table
‘student’ through MySQL-Python connectivity

import mysql.connector as ms
db=ms.connect(host="localhost",
user="root",
passwd="root",
database="class_xii"
)
#cn=db.cursor()
def insert_rec():
try:
while True:
rn=int(input("Enter roll number:"))
sname=input("Enter name:")
marks=float(input("Enter marks:"))
gr=input("Enter grade:")
cn.execute("insert into student values({},'{}',{},'{}')".format(rn,sname,marks,gr))
db.commit()
ch=input("Want more records? Press (N/n) to stop entry:")
if ch in 'Nn':
print("Record Inserted ")
break
except Exception as e:
print("Error", e)
def update_rec():
try:
rn=int(input("Enter rollno to update:"))
marks=float(input("Enter new marks:"))
gr=input("Enter Grade:")
cn.execute("update student set marks={},gr='{}' where rn={}".format(marks,gr,rn))
db.commit()
print("Record Updated.... ")
except Exception as e:
print("Error",e)
def delete_rec():
try:
rn=int(input("Enter rollno to delete:"))
cn.execute("delete from student where rn={}".format(rn))
db.commit()
print("Record Deleted ")
except Exception as e:
print("Error",e)

def view_rec():
try:
cn.execute("select * from student")
records = cn.fetchall()
for record in records:
print(record)
#db.commit()
#print("Record...")
except Exception as e:
print("Error",e)
db = ms.connect( host="localhost",
user="root",
passwd="root",
database="class_xii"
)
cn = db.cursor()
while True:
print("MENU\n1. Insert Record\n2. Update Record \n3. Delete Record\n4. Display Record \n5.Exit")
ch=int(input("Enter your choice<1-4>="))
if ch==1:
insert_rec()
elif ch==2:
update_rec()
elif ch==3:
delete_rec()
elif ch==4:
view_rec()
elif ch==5:
break
else:
print("Wrong option selected")
OUTPUT:

MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=1
Enter roll number:101
Enter name:Ramesh
Enter marks:85
Enter grade:A
Want more records? Press (N/n) to stop entry:n
Record Inserted
MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=4
(101, 'Ramesh', 85.0, 'A')
MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=2
Enter rollno to update:101
Enter new marks:58
Enter Grade:B
Record Updated....
MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=4
(101, 'Ramesh', 58.0, 'B')
MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=5
Program 19
Write a program to connect Python with MySQL using database connectivity and perform
the following operation on data in database: Fetch records from the table using fetchall()

import sqlite3

def getAllRows():
try:
connection = sqlite3.connect('SQLite_Python.db')
cursor = connection.cursor()
print("Connected to SQLite")

sqlite_select_query = """SELECT * from database_developers"""


cursor.execute(sqlite_select_query)
records = cursor.fetchall()
print("Total rows are: ", len(records))
print("Printing each row")
for row in records:
print("Id: ", row[0])
print("Name: ", row[1])
print("Email: ", row[2])
print("Salary: ", row[3])
print("\n")

cursor.close()

except sqlite3.Error as error:


print("Failed to read data from table", error)
finally:
if connection:
connection.close()
print("The Sqlite connection is closed")

getAllRows()

Output
Connected to database
Total rows are: 5

Printing each row

Id: 1

Name: Emma

Email: emma@pynative.com
Salary: 12000.0

Id: 2

Name: Scott

Email: scott@pynative.com

Salary: 22000.0

Id: 3

Name: Jessa

Email: jessa@pynative.com

Salary: 18000.0

Id: 4

Name: Mike

Email: mike@pynative.com

Salary: 13000.0

Id: 5

Name: Ricky
Email: ricky@pynative.com

Salary: 19000.0

The Sqlite connection is closed

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy