0% found this document useful (0 votes)
254 views24 pages

Class XII Computer Science Practical Guide

The document contains practical assignments on Python and SQL for class 12 computer science students. The assignments cover topics like implementing a stack using a list in Python, pushing numbers divisible by 5 into a stack, SQL queries on teacher, product, client, doctor and sender tables, and integrating Python with MySQL.

Uploaded by

Forzen flames
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
254 views24 pages

Class XII Computer Science Practical Guide

The document contains practical assignments on Python and SQL for class 12 computer science students. The assignments cover topics like implementing a stack using a list in Python, pushing numbers divisible by 5 into a stack, SQL queries on teacher, product, client, doctor and sender tables, and integrating Python with MySQL.

Uploaded by

Forzen flames
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PRACTICAL LIST OF CLASS XII COMPUTER SCIENCE

1) Write a Python program to implement a stack using list (PUSH & POP
Operation on Stack).
2) Write a python program using function PUSH(Arr), where Arr is a list of
numbers. From this list push all numbers divisible by 5 into a stack
implemented by using a list. Display the stack if it has at least one
element, otherwise display appropriate error message.
3) Write a python program using function POP(Arr), where Arr is a stack
implemented by a list of numbers. The function returns the value deleted
from the stack.

4) Write the SQL Queries of the TEACHERS Table1.


Table :Teacher

NO NAME AGE DEPARTMENT DOJ SALARY GENDER


1 Jujal 34 Computer 10/01/97 22000 M
2 Sharmila 31 History 24/03/98 30000 F
3 Sandeep 32 Maths 12/12/96 35000 M
4 Rakesh 42 History 01/07/99 30000 M
5 Neelam 33 Maths 25/02/97 21000 F
(i) Write a command to create the Teacher table.
(ii) Write the query to insert the given 5 record in teachers table.
(iii) To show all the information about the teachers of History department.
(iv) To list the names of the female teachers who are in Maths department.
(v) To list the name of the teachers with their date of joining in ascending
order.
(vi) To display the name of the teachers whose name starts with ‘R’ and
end with ‘h’.
(vii) To count number of teachers with age less than 42.

5) Write the SQL Queries of the Following Tables: Product and Client.
Table: PRODUCT

P_ID Product Name Manufacturer Price


TP01 TalcomPowder LAK 40
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95

Table: CLIENT
C_ID Client Name City P_ID
01 TalcomPowder Delhi FW05
06 Face Wash Mumbai BS01
12 Bath Soap Delhi SH06
15 Shampoo Delhi FW12
16 Face Wash Banglore TP01

(i) To display the details of those Clients whose city is Delhi.


(ii) To display the details of Products whose Price is in the range of 50 to
100(Both values included).
(iii) To display the ClientName, City from table Client, and ProductName and
Price from table Product, with their corresponding matching P_ID.
(iv) To increase the Price of all Products by 10
(v) SELECT DISTINCT Address FROM Client.
(vi) SELECT Manufacturer, MAX(Price), Min(Price), Count(*) FROM
Product GROUP BY Manufacturer;
(vii) SELECT ClientName, ManufacturerName FROM Product, Client
WHERE Client.Prod_Id=Product.P_Id;
(viii) SELECT ProductName, Price * 4 FROM Product.

6) Write the SQL Queries of the Following Tables: Doctors and Salary.
TABLE: DOCTOR

ID NAME DEPT SEX EXPERIENCE


101 Johan ENT  M   12
104 Smith ORTHOPEDIC  M   5
107 George CARDIOLOGY  M   10
114 Lara SKIN  F   3
109 K George MEDICINE  F   9
105 Johnson ORTHOPEDIC  M   10
117 Lucy ENT  F   3
111 Bill MEDICINE  F   12
130 Murphy ORTHOPEDIC  M   15

TABLE: SALARY

ID BASIC ALLOWANCE CONSULTAION


101 12000   1000   300
104 23000   2300   500
107 32000   4000   500
114 12000   5200   100
109 42000   1700   200
105 18900   1690   300
130 21700   2600   300
(i) Display NAME of all doctors who are in “MEDICINE” having more than 10
years experience from the Table DOCTOR.
(ii) Display the average salary of all doctors working in “ENT”department
using the tables. DOCTORS and SALARY Salary =BASIC+ALLOWANCE.
(iii) Display the minimum ALLOWANCE of female doctors.
(iv) Display the highest consultation fee among all male doctors.
(v) SELECT count (*) from DOCTOR where SEX = “F”
(vi) SELECT NAME, DEPT , BASIC from DOCTOR, SALRY Where DEPT
= “ENT” AND DOCTOR.ID = SALARY.ID

7) Write the SQL Queries of the Following Tables: Sender and Recipient.

TABLE : SENDER

SenderID SenderName Sender Address Sender City


ND01 R jain 2,ABC Appts New Delhi
MU02 H sinha 12, Newton Mumbai
MU1 5 S haj 27/ A,Park Street New Delhi
ND5 0 T Prasad 122-K,SDA Mumbai

TABLE :RECIPIENT

RecID SenderID ReCName RecAddress ReCCity


KO05 ND01 RBajpayee 5,Central Avenue Kolkata
ND08 MU0 2 S Mahajan 116, A Vihar NewDelhi
MU19 ND01 H sing 2A,Andheri East Mumbai
MU32 MU1 5 PK Swamy B5, CS erminus Mumbai
ND48 ND50 S Tripathi 13, B1 D,Mayur Vihar NewDelhi
(i) To display the names of all senders from Mumbai.
(ii) To display the recID, senderName, senderAddress, RecName, RecAddress
for every recipt.
(iii) To display the sender details in ascending order of SenderName.
(iv) To display number of Recipients from each city.
(v) SELECT DISTINCT SenderCity FROM Sender;
(vi) SELECT A.SenderName A, B.RecName FROM Sender A, Recipient B
WHERE A.SenderID=B. SenderID AND B.RecCity=’Mumbai’;
(vii) SELECT RecName,RecAddress FROM Recipient WHERE RecCity Not
IN (‘Mumbai’,Kolkata’);
(viii) SELECT RecID, RecName FROM Recipient WHERE SenderID = ‘MU02’ OR
SenderID = ‘ND50’;
8) Integrate MySQL with Python by importing the MySQL module and add
records of student and display all the record.
9) ntegrate MySQL with Python by importing the MySQL module to search
student using rollno, name, age, class and if present in table display the
record, if not display appropriate method.
10) Integrate SQL with Python by importing the MySQL module to search a
student using rollno, update the record.
11) Integrate SQL with Python by importing the MySQL module to search a
student using rollno, delete the record.

Answer :

XII CS – Practical Assignments for TERM 2


Assignment 1:
Write a Python program to implement a stack using list (PUSH & POP Operation on
Stack).
Ans:
def isEmpty(s):
    if len(s)==0:
        return True
    else:
        return False

def push(s,item):
    s.append(item)
    top=len(s)-1
    
def pop(s):
    if isEmpty(s):
        return 'Underflow occurs'
    else:
        val=s.pop()
        if len(s)==0:
            top=None
        else:
            top=len(s)-1
        return val

def peek(s):
    if isEmpty(s):
        return 'Underflow occurs'
    else:
        top=len(s)-1
        return s[top]
    
def show(s):
    if isEmpty(s):
        print('no item found')
    else:
        t=len(s)-1
        print('(TOP)',end='')
        while(t>=0):
            print(s[t],'<==',end='')
            t=t-1
        print()

s=[]
top=None
while True:
    print('****** STACK IMPLEMENTATION USING LIST ******')
    print('1: PUSH')
    print('2: POP')
    print('3: PEEK')
    print('4: Show')

    print('0: Exit')
    ch=int(input('Enter choice:'))
    if ch==1:
        val=int(input('Enter no to push:'))
        push(s,val)
    elif ch==2:
        val=pop(s)
        if val=='Underflow':
            print('Stack is empty')
        else:
            print('\nDeleted item is:',val)
    elif ch==3:
        val=peek(s)
        if val=='Underflow':
            print('Stack is empty')
        else:
            print('\nTop item is:',val)
    elif ch==4:
        show(s)
    elif ch==0:
        print('Bye')
        break
        
            

Output is:
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: PEEK
4: Show
0: Exit
Enter choice:1
Enter no to push:23
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: PEEK
4: Show
0: Exit
Enter choice:4
(TOP)23 <==
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: PEEK
4: Show
0: Exit
Enter choice:1
Enter no to push:23
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: PEEK
4: Show
0: Exit
Enter choice:2

Deleted item is: 23


****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: PEEK
4: Show
0: Exit
Enter choice:3

Top item is: 23


****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: PEEK
4: Show
0: Exit
Enter choice:0
Bye

Assignment 2:

Write a python program using function PUSH(Arr), where Arr is a list of numbers.
From this list push all numbers divisible by 5 into a stack implemented by using a
list. Display the stack if it has at least one element, otherwise display appropriate
error message.

Ans:
def isEmpty(Arr):
    if len(Arr)==0:
        return True
    else:
        return False

def push(Arr,item):
    if item%5==0:
        Arr.append(item)
        top=len(Arr)-1
    
def show(Arr):
    if isEmpty(Arr):
        print('No item found')
    else:
        t=len(Arr)-1
        print('(TOP)',end='')
        while(t>=0):
            print(Arr[t],'<==',end='')
            t=t-1
        print()

Arr=[]
top=None
while True:
    print('****** STACK IMPLEMENTATION USING LIST ******')
    print('1: PUSH')
    print('2: Show')
    print('0: Exit')
    ch=int(input('Enter choice:'))
    if ch==1:
        val=int(input('Enter no to push:'))
        push(Arr,val)
    elif ch==2:
        show(Arr)
    elif ch==0:
        print('Bye')
        break
        

        
    
    
Output is:
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: Show
0: Exit
Enter choice:1
Enter no to push:23
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: Show
0: Exit
Enter choice:1
Enter no to push:20
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: Show
0: Exit
Enter choice:2
(TOP)20 <==
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: Show
0: Exit
Enter choice:0
Bye
>>>

Assignment 3:

Write a python program using function POP(Arr), where Arr is a stack implemented
by a list of numbers. The function returns the value deleted from the stack.

Ans:
def isEmpty(Arr):
    if len(Arr)==0:
        return True
    else:
        return False

def push(Arr,item):
    Arr.append(item)
    top=len(Arr)-1
    
def pop(Arr):
    if isEmpty(Arr):
        return 'Underflow occurs'
    else:
        val=Arr.pop()
        if len(Arr)==0:
            top=None
        else:
            top=len(Arr)-1
        return val
 
def show(Arr):
    if isEmpty(Arr):
        print('no item found')
    else:
        t=len(Arr)-1
        print('(TOP)',end='')
        while(t>=0):
            print(Arr[t],'<==',end='')
            t=t-1
        print()

Arr=[]
top=None
while True:
    print('****** STACK IMPLEMENTATION USING LIST ******')
    print('1: PUSH')
    print('2: POP')
    print('3: Show')
    print('0: Exit')
    ch=int(input('Enter choice:'))
    if ch==1:
        val=int(input('Enter no to push:'))
        push(Arr,val)
    elif ch==2:

        val=pop(Arr)
        if val=='Underflow':
            print('Stack is empty')
        else:
            print('\nDeleted item is:',val)
    
    elif ch==3:
        show(Arr)
    elif ch==0:
        print('Bye')
        break
        
        
    
    
    
    
        
    
    
    

Output is:
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: Show
0: Exit
Enter choice:1
Enter no to push:34
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: Show
0: Exit
Enter choice:1
Enter no to push:3
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: Show
0: Exit
Enter choice:3
(TOP)3 <==34 <==
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: Show
0: Exit
Enter choice:2

Deleted item is: 3


****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: Show
0: Exit
Enter choice:3
(TOP)34 <==
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: Show
0: Exit
Enter choice:0
Bye
>>>
Mysql :
2. Product and Clent

(i) To display the details of those Clients whose city is Delhi.

Ans: Select all from Client where City=”Delhi”

(ii) To display the details of Products whose Price is in the range of 50 to 100(Both values included).

Ans: Select all from product where Price between 50 and 100

(iii) To display the ClientName, City from table Client, and ProductName and Price from table Product, with their
corresponding matching P_ID.

Ans: Select ClientName,City,ProductName, Price from Product,Client where Product.P_ID=Client.P_ID.

(iv) To increase the Price of all Products by 10

Ans: Update Product Set Price=Price +10

(v) SELECT DISTINCT Address FROM Client.


Ans: ( The above question may consist DISTINCT City. If it is DISTINCT City, the following is the answer)

City
-----
Delhi
Mumbai
Bangalore

(vi) SELECT Manufacturer, MAX(Price), Min(Price), Count(*) FROM Product GROUP BY Manufacturer;

Ans:

Manufacturer    Max(Price)    Min(Price)    Count(*)


   LAK                      40                   40                 1
   ABC                      55                   45                2
   XYZ                      120                 95                 2

(vii) SELECT ClientName, ManufacturerName FROM Product, Client WHERE Client.Prod_Id=Product.P_Id;

Ans:

ClientName                ManufacturerName
Cosmetic Shop            ABC
Total Health                  ABC
Live Life                          XYZ
Pretty Woman               XYZ
Dreams                         LAK

(viii) SELECT ProductName, Price * 4 FROM Product.

ProductName          Price*4
 Talcom Poweder       160
 Face Wash                 180
 Bath Soap                   220
 Shampoo                    480
 Face Wash                 380

3.Doctor and Salary

(i) Display NAME of all doctors who are in “MEDICINE” having more than 10 years experience from the Table
DOCTOR.

Ans: Select Name from Doctor where Dept=”Medicine” and Experience>10

(ii) Display the average salary of all doctors working in “ENT”department using the tables. DOCTORS and
SALARY Salary =BASIC+ALLOWANCE.

Ans: Select avg(basic+allowance) from Doctor,Salary where Dept=”Ent” and Doctor.Id=Salary.Id

(iii) Display the minimum ALLOWANCE of female doctors.


Ans: Select min(Allowance) from Doctro,Salary where Sex=”F” and Doctor.Id=Salary.Id

(iv) Display the highest consultation fee among all male doctors.

Ans: Select max(Consulation) from Doctor,Salary where Sex=”M” and Doctor.Id=Salary.Id

(v) SELECT count (*) from DOCTOR where SEX = “F”

Ans: 4

(vi) SELECT NAME, DEPT , BASIC from DOCTOR, SALRY Where DEPT = “ENT” AND DOCTOR.ID =
SALARY.ID

Ans:      Name           Dept Basic


            Jonah Ent        12000

4. Sender and Recipient


(i) To display the names of all senders from Mumbai.

Ans: Select * from Sender where SenderCity =’Mumbai’;

(ii) To display the recID, senderName, senderAddress, RecName, RecAddress for every recipt.

Ans: Select recID, SenderName, SenderAddress, RecName, RecAddress from Sender, Recipient where
Sender.Senderid=Recipient.RenderId;

(iii) To display the sender details in ascending order of SenderName.

Ans: Select * from Sender order by SenderName;

(iv) To display number of Recipients from each city.

Ans: Select RecCity,Count(*) from Recipient group by RecCity;

(vi) SELECT A.SenderName A, B.RecName FROM Sender A, Recipient B WHERE A.SenderID=B. SenderID


AND B.RecCity=’Mumbai’;

Ans:     SenderName     RecName
               R.Jain               H.Singh
               S.Jha                P.K.Swamy

(vii) SELECT RecName,RecAddress FROMRecipient WHERE RecCity Not IN (‘Mumbai’,Kolkata’);

Ans:      RecName      RecAddressS


               Mahajan         116, A Vihar
               S Tripati          13, B1 D, Mayur Vihar

(viii) SELECT RecID, RecName FROM Recipient WHERE SenderID = ‘MU02’ OR SenderID = ‘ND50’;
Ans: RecID        RecName
              ND08         S Mahajan
              ND48         S Tripathi

Assignment 5:
Integrate MySQL with Python by importing the MySQL module and add records of
student and display all the record.
Ans:
import os
import platform
import mysql.connector

mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",databas
e="student",charset="utf8")
print(mydb)
mycursor=mydb.cursor()

def stuInsert():
    L=[]
    roll=int(input("Enter the roll number : "))
    L.append(roll)
    name=input("Enter the Name: ")
    L.append(name)
    age=int(input("Enter Age of Student : "))
    L.append(age)
    clas=input("Enter the Class : ")
    L.append(clas)
    
    stud=(L)
    sql="insert into stud (roll,name,age,clas) values (%s,%s,%s,%s)"
    mycursor.execute(sql,stud)
    mydb.commit()
def stuview():
    mycursor.execute("select * from stud")
    myrus=mycursor.fetchall()
    for x in myrus:
        print(x)

def MenuSet(): #Function For The Student Management System


    print("Enter 1 : To Add Student")
    print("Enter 2 : To View Students")
    userInput = int(input("Please Select An Above Option: ")) #Will Take Input From
User
    if(userInput == 1):
        stuInsert()
    if(userInput == 2):
        stuview()    
MenuSet()
def runAgain():
    runAgn = input("\nwant To Run Again Y/n: ")
    while(runAgn.lower() == 'y'):
        if(platform.system() == "Windows"):
            print(os.system('cls'))
        else:
            print(os.system('clear'))
        MenuSet()
        runAgn = input("\nwant To Run Again y/n: ")
        
runAgain()

Output is:
<mysql.connector.connection.MySQLConnection object at 0x02272110>
Enter 1 : To Add Student
Enter 2 : To View Students
Please Select An Above Option: 2
(1, 'ANJU JHA', 17, 12)
(2, 'YASH', 16, 11)
(3, 'ANIKET JAISWAR', 16, 12)
(4, 'SANGEETA', 15, 10)
(5, 'SANGEETA SETH', 15, 10)
(6, 'YAMINI', 16, 11)
(7, 'ANJU', 15, 10)
(8, 'OM', 16, 12)
(9, 'MANGALA', 16, 11)

want To Run Again Y/n: Y


0
Enter 1 : To Add Student
Enter 2 : To View Students
Please Select An Above Option: 1
Enter the roll number : 10
Enter the Name: MALINI
Enter Age of Student : 17
Enter the Class : 12

want To Run Again y/n: Y


0
Enter 1 : To Add Student
Enter 2 : To View Students
Please Select An Above Option: 2
(1, 'ANJU JHA', 17, 12)
(2, 'YASH', 16, 11)
(3, 'ANIKET JAISWAR', 16, 12)
(4, 'SANGEETA', 15, 10)
(5, 'SANGEETA SETH', 15, 10)
(6, 'YAMINI', 16, 11)
(7, 'ANJU', 15, 10)
(8, 'OM', 16, 12)
(9, 'MANGALA', 16, 11)
(10, 'MALINI', 17, 12)

want To Run Again y/n: 

Assignment 6:
Integrate MySQL with Python by importing the MySQL module to search student
using rollno, name, age, class  and if present in table display the record, if not
display appropriate method.
Ans:
import os
import platform
import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
                             user="root",\
                             passwd="root",\
                             database="student",charset="utf8")
print(mydb)
mycursor=mydb.cursor()

def stuview():
    print("Select the search criteria : ")
    print("1. Roll")
    print("2. Name")
    print("3. Age")
    print("4. Class")
    print("5. All")
    ch=int(input("Enter the choice : "))
    if ch==1:
        s=int(input("Enter roll no : "))
        rl=(s,)
        sql="select * from stud where roll=%s"
        mycursor.execute(sql,rl)
    elif ch==2:
        s=input("Enter Name : ")
        rl=(s,)
        sql="select * from stud where name=%s"
        mycursor.execute(sql,rl)
    elif ch==3:
        s=int(input("Enter age : "))
        rl=(s,)
        sql="select * from stud where age=%s"
        mycursor.execute(sql,rl)
    elif ch==4:
        s=input("Enter Class : ")
        rl=(s,)
        sql="select * from stud where clas=%s"
        mycursor.execute(sql,rl)
    elif ch==5:
        sql="select * from stud"
        mycursor.execute(sql)   
    res=mycursor.fetchall()
    print("The Students details are as follows : ")
    print("(ROll, Name, Age, Class)")
    for x in res:
        print(x)

def MenuSet(): #Function For The Student Management System


    print("Enter 1 : To Search Student")
    userInput = int(input("Please Select An Above Option: ")) #Will Take Input From
User
    if(userInput == 1):
        stuview()    
MenuSet()
def runAgain():
    runAgn = input("\nwant To Run Again Y/n: ")
    while(runAgn.lower() == 'y'):
        if(platform.system() == "Windows"):
            print(os.system('cls'))
        else:
            print(os.system('clear'))
        MenuSet()
        runAgn = input("\nwant To Run Again y/n: ")
        
runAgain()

Output is:
<mysql.connector.connection.MySQLConnection object at 0x022720F0>
Enter 1 : To Search Student
Please Select An Above Option: 1
Select the search criteria : 
1. Roll
2. Name
3. Age
4. Class
5. All
Enter the choice : 1
Enter roll no : 8
The Students details are as follows : 
(ROll, Name, Age, Class)
(8, 'OM', 16, 12)

want To Run Again Y/n: y


0
Enter 1 : To Search Student
Please Select An Above Option: 1
Select the search criteria : 
1. Roll
2. Name
3. Age
4. Class
5. All
Enter the choice : 2
Enter Name : MALINI
The Students details are as follows : 
(ROll, Name, Age, Class)
(10, 'MALINI', 17, 12)

want To Run Again y/n: Y


0
Enter 1 : To Search Student
Please Select An Above Option: 1
Select the search criteria : 
1. Roll
2. Name
3. Age
4. Class
5. All
Enter the choice : 3
Enter age : 15
The Students details are as follows : 
(ROll, Name, Age, Class)
(4, 'SANGEETA', 15, 10)
(5, 'SANGEETA SETH', 15, 10)
(7, 'ANJU', 15, 10)

want To Run Again y/n: Y


0
Enter 1 : To Search Student
Please Select An Above Option: 1
Select the search criteria : 
1. Roll
2. Name
3. Age
4. Class
5. All
Enter the choice : 4
Enter Class : 12
The Students details are as follows : 
(ROll, Name, Age, Class)
(1, 'ANJU JHA', 17, 12)
(3, 'ANIKET JAISWAR', 16, 12)
(8, 'OM', 16, 12)
(10, 'MALINI', 17, 12)

want To Run Again y/n: Y


0
Enter 1 : To Search Student
Please Select An Above Option: 1
Select the search criteria : 
1. Roll
2. Name
3. Age
4. Class
5. All
Enter the choice : 5
The Students details are as follows : 
(ROll, Name, Age, Class)
(1, 'ANJU JHA', 17, 12)
(2, 'YASH', 16, 11)
(3, 'ANIKET JAISWAR', 16, 12)
(4, 'SANGEETA', 15, 10)
(5, 'SANGEETA SETH', 15, 10)
(6, 'YAMINI', 16, 11)
(7, 'ANJU', 15, 10)
(8, 'OM', 16, 12)
(9, 'MANGALA', 16, 11)
(10, 'MALINI', 17, 12)

want To Run Again y/n: N


>>>

Assignment 7:
Integrate MySQL with Python by importing the MySQL module to search a student
using rollno, delete the record.
Ans:

import os
import platform
import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
                             user="root",\
                             passwd="root",\
                             database="student",charset="utf8")
print(mydb)
mycursor=mydb.cursor()

def removeStu():
    roll=int(input("Enter the roll number of the student to be deleted : "))
    rl=(roll,)
    sql="Delete from stud where roll=%s"
    mycursor.execute(sql,rl)
    print('Record deleted!!!')
    mydb.commit()
    
def stuview():
    mycursor.execute("select * from stud")
    myrus=mycursor.fetchall()
    for x in myrus:
        print(x)

def MenuSet(): #Function For The Student Management System


    print("Enter 1 : To Delete Student")
    print("Enter 2 : To View Students")
    userInput = int(input("Please Select An Above Option: ")) #Will Take Input From
User
    if(userInput == 1):
        removeStu()
    if(userInput == 2):
        stuview()    
MenuSet()
def runAgain():
    runAgn = input("\nwant To Run Again Y/n: ")
    while(runAgn.lower() == 'y'):
        if(platform.system() == "Windows"):
            print(os.system('cls'))
        else:
            print(os.system('clear'))
        MenuSet()
        runAgn = input("\nwant To Run Again y/n: ")
runAgain()

Output is:
<mysql.connector.connection.MySQLConnection object at 0x02272050>
Enter 1 : To Delete Student
Enter 2 : To View Students
Please Select An Above Option: 2
(1, 'ANJU JHA', 17, 12)
(2, 'YASH', 16, 11)
(3, 'ANIKET JAISWAR', 16, 12)
(4, 'SANGEETA', 15, 10)
(5, 'SANGEETA SETH', 15, 10)
(6, 'YAMINI', 16, 11)
(7, 'ANJU', 15, 10)
(8, 'OM', 16, 12)
(9, 'MANGALA', 16, 11)
(10, 'MALINI', 17, 12)

want To Run Again Y/n: y


0
Enter 1 : To Delete Student
Enter 2 : To View Students
Please Select An Above Option: 1
Enter the roll number of the student to be deleted : 8
Record deleted!!!

want To Run Again y/n: y


0
Enter 1 : To Delete Student
Enter 2 : To View Students
Please Select An Above Option: 2
(1, 'ANJU JHA', 17, 12)
(2, 'YASH', 16, 11)
(3, 'ANIKET JAISWAR', 16, 12)
(4, 'SANGEETA', 15, 10)
(5, 'SANGEETA SETH', 15, 10)
(6, 'YAMINI', 16, 11)
(7, 'ANJU', 15, 10)
(9, 'MANGALA', 16, 11)
(10, 'MALINI', 17, 12)

want To Run Again y/n: n

Assignment 8:
Integrate SQL with Python by importing the MySQL module to search a student
using rollno, update the record.
Ans:
import mysql.connector as mycon
cn =
mycon.connect(host='localhost',user='root',password="root",database="student",char
set="utf8")
cur = cn.cursor()
print('Welcome to student Details Updation screen... ')

print("*******************EDIT STUDENT DETAILS **************************")


ro = int(input("Enter Student's roll number to edit :"))
query="select * from stud where roll="+str(ro)
cur.execute(query)
results = cur.fetchall()
if cur.rowcount<=0:
    print("\## SORRY! NO MATCHING DETAILS AVAILABLE ##")
else:
    print("**************************************************")
    print('%5s'%"ROLL NO",'%15s'%'NAME','%12s'%'AGE','%10s'%'CLASS')
    print("**************************************************")
    for row in results:
        print('%5s' % row[0],'%15s'%row[1],'%12s'%row[2],'%10s'%row[3])
print("-"*50)
ans = input("Are you sure to update ? (y/n)")
if ans=="y" or ans=="Y":
    d = input("Enter new name to update (enter old value if not to update) :")
    s = int(input("Enter new age to update (enter old value if not to update) :"))
    
    query="update stud set name='"+d+"',age="+str(s) + " where roll="+str(ro)
    
    cur.execute(query)
    cn.commit()
    print("\n## RECORD UPDATED  ##")    

Output is:
Welcome to student Details Updation screen... 
*******************EDIT STUDENT DETAILS **************************
Enter Student's roll number to edit :1
**************************************************
ROLL NO            NAME          AGE      CLASS
**************************************************
    1        ANJU JHA           17         12
--------------------------------------------------
Are you sure to update ? (y/n)y
Enter new name to update (enter old value if not to update) :ANJU
Enter new age to update (enter old value if not to update) :16

## RECORD UPDATED  ##

You might also like