Term 2
Term 2
COMPUTER SCIENCE
PRACTICAL RECORD
(TERM- 2)
CLASS : XII
2021-2022
Acknowledgement
I, ……………………………. of
class XII – Section A would like to express
my sincere gratitude to Mrs. Shiny George
Madam, Principal Kendriya Vidyalaya
Bhandup.
express our gratitude to our school
KENDRIYA VIDYALAYA AMBARNATH .
Signature:
(Subject Teacher)
Internal Examiner
External
Examiner
Date: / / 2022
Principal
INDEX
XII CS – Practical Assignments for TERM 2
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
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):
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
0: Exit
Enter choice:3
(TOP)34 <==
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: Show
0: Exit
Enter choice:0
Bye
>>>
Assignment 4: SQL Commands on EMPLOYEE table
MySQL Practical
1
. . CREATING TABLES IN MYSQL
E.g. in order to create table EMPLOYEE given below :
ECODE ENAME GENDER GRADE GROSS
We write the following
command :
CREATE TABLE
employee( ECODE
integer ,
ENAME
varchar(20) ,
GENDER
char(1) ,
GRADE
char(2) ,
GROSS
integer
);
2
. INSERTING DATA INTO TABLE
- e.g. to enter a row into EMPLOYEE table (created above), we write command as :
INSERT INTO employee VALUES(1001 , ‘Ravi’ , ‘M’ , ‘E4’ , 50000);
OR
INSERT INTO employee (ECODE , ENAME , GENDER , GRADE , GROSS) VALUES(1001 , ‘Ravi’ , ‘M’ , ‘E4’ , 50000);
3
. INSERTING NULL VALUES
- To insert value NULL in a specific column, we can type NULL without quotes and NULL will be
inserted in thatcolumn. E.g. in order to insert NULL value in ENAME column of above table, we write
INSERT command as :
4
. SIMPLE QUERY USING SELECT COMMAND
- The SELECT command is used to pull information from a table.
- In order to retrieve everything (all columns) from a table, SELECTcommand is used as :
SELECT * FROM <tablename> ;
e.g.In order to retrieve everything from Employee table, we write SELECT command as :
EMPLOYEE
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 NULL M B2 38965
5
. SELECTING PARTICULAR COLUMNS
EMPLOYEE
FROM EMPLOYEE ;
E.g.2 in order to select only ENAME, GRADE and GROSS column, the command is :
SELECT ENAME , GRADE , GROSS
FROM EMPLOYEE ;
6
. SELECTING PARTICULAR ROWS
We can select particular rows from a table by specifying a condition through WHERE clause along with
SELECTstatement. E.g. In employee table if we want to select rows where Gender is female, then
command is :
SELECT * FROM EMPLOYEE
E.g.2. in order to select rows where salary is greater than 48000, then
command is :SELECT * FROM EMPLOYEE
WHERE GROSS > 48000 ;
7
. ELIMINATING REDUNDANT DATA
The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement. For example ,
SELECT GENDER FROM EMPLOYEE ;
GENDER
M
M
F
M
F
F
DISTINCT(GENDER)
M
F
8
. VIEWING STRUCTURE OF A TABLE
- If we want to know the structure of a table, we can use DESCRIBE or DESC command, as per following syntax :
DESCRIBE | DESC <tablename> ;
e.g. to view the structure of table EMPLOYEE, commandis : DESCRIBE EMPLOYEE ; OR DESC EMPLOYEE ;
9
. USING COLUMN ALIASES
- The columns that we select in a query can be given a different name, i.e. column alias name for output purpose.
e.g. In output, suppose we want to display ECODE column as EMPLOYEE_CODE in output , then
command is :SELECT ECODE AS “EMPLOYEE_CODE”
FROM EMPLOYEE ;
1
0
. CONDITION BASED ON A RANGE
- The BETWEEN operator defines a range of values that the column values must fall in to make the condition
true. Therange include both lowervalue and uppervalue.
e.g. to display ECODE, ENAME and GRADE of those employees whose salary is between 40000 and 50000,
commandis:
SELECT ECODE , ENAME
,GRADEFROM
EMPLOYEE
WHERE GROSS BETWEEN 40000 AND 50000 ;
Output will be :
ECODE ENAME GRADE
1001 Ravi E4
1006 Ruby A1
1
. CONDITION BASED ON A LIST
- To specify a list of values, IN operator is used. The IN operator selects value that match any value in a
given list ofvalues. E.g.
SELECT * FROM
EMPLOYEE WHERE
GRADE IN (‘A1’ , ‘A2’);
Output will be :
ECODE ENAME GENDER GRADE GROSS
1002 Akash M A1 35000
1006 Ruby F A1 45000
1005 Sunny M A2 30000
1009 Neema F A2 52000
- The NOT IN operatorfinds rows that do not match in the list. E.g.
SELECT * FROM EMPLOYEE
WHERE GRADE NOT IN (‘A1’ , ‘A2’);
Output will be :
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000
1004 Neela F B2 38965
1
2
. CONDITION BASED ON PATTERN MATCHES
- LIKE operator is used for pattern matching in SQL. Patterns are described using two special wildcard characters:
e.g. to display names of employee whose name starts with R in EMPLOYEE table, the command is :
SELECT ENAME FROM EMPLOYEE
Output will be :
ENAME
Ravi
Ruby
Output will be :
ECODE ENAME GENDER GRADE GROSS
1004 Neela F B2 38965
1009 Neema F A2 52000
Output will be :
ECODE ENAME GENDER GRADE GROSS
1005 Sunny M A2 30000
1006 Ruby F A1 45000
1
3
. SEARCHING FOR NULL
- The NULL value in a column can be searched for in a table using IS NULL in the WHERE clause. E.g. to list
employeedetails whose salary contain NULL, we use the command :
SELECT *
FROM EMPLOYEE
e.g.
STUDENT
Roll_No Name Marks
1 ARUN NULL
2 RAVI 56
4 SANJAY NULL
to display the names of those students whose marks is NULL, we use the
command :SELECT Name
FROM EMPLOYEE
Output will be :
Name
ARUN
SANJAY
14. SORTING RESULTS
Whenever the SELECT query is executed , the resulting rows appear in a predecided order. The ORDER BY
clause allowsorting of query result. The sorting can be done either in ascending or descending order, the
default is ascending.
e.g. to display the details of employees in EMPLOYEE table in alphabetical order, we use
command :SELECT *
FROM
EMPLOYEE
ORDER BY
ENAME ;
Output will be :
ECODE ENAME GENDER GRADE GROSS
1002 Akash M A1 35000
1004 Neela F B2 38965
1009 Neema F A2 52000
1001 Ravi M E4 50000
1006 Ruby F A1 45000
1005 Sunny M A2 30000
e.g. display list of employee in descending alphabetical order whose salary is greater than 40000.
SELECT ENAME
FROM
EMPLOYEE
WHERE GROSS >
40000 ORDER BY
ENAME desc ;
Output will be :
ENAME
Ravi
Ruby
Neema
e.g. to change the salary of employee of those in EMPLOYEE table having employee code 1009 to 55000.
UPDATE EMPLOYEE SET GROSS = 55000 WHERE ECODE = 1009 ;
OTHER EXAMPLES
Increase the salary of each employee by 1000 in the EMPLOYEE table.
UPDATE EMPLOYEE
Change the grade to ‘A2’ for those employees whose employee code is 1004 and name is Neela.
UPDATE EMPLOYEE
SET GRADE=’A2’
WHERE <condition> ;
For example, to remove the details of those employee from EMPLOYEE table whose grade is A1.
DELETE FROM EMPLOYEE
So if we do not specify any condition with WHERE clause, then all the rows of the table will be deleted.
Thus aboveline will delete all rows from employee table.
Once this command is given, the table name is no longer recognized and no more commands can be given on
that table.After this command is executed, all the data in the table along with table structure will be deleted.
e.g. Given a table namely Testt with the following data in it.
Col1 Col2
1 A
2 G
Now following commands are given for the table. Predict the table contents after each of the following statements:
(i) ALTER TABLE testt ADD col3 INT ;
(ii) ALTER TABLE testt ADD col4 INT NOT NULL ;
(iii) ALTER TABLE testt ADD col5 CHAR(3) NOT NULL ;
(iv) ALTER TABLE testtADD col6 VARCHAR(3);
22.MODIFYING COLUMNS
In table EMPLOYEE, change the column GROSS to SALARY.
In table EMPLOYEE , change the column ENAME to EM_NAME and data type from
VARCHAR(20) toVARCHAR(30).
In table EMPLOYEE , change the datatype of GRADE column from CHAR(2) to VARCHAR(2).
ALTER TABLE EMPLOYEE
To delete a column from a table, the ALTER TABLE command takes the following form :
DROP GRADE ;
Table : EMPL
1. AVG( )
This function computes the average of given data.
e.g. SELECT AVG(SAL)
FROM EMPL ;
Output
AVG(SAL)
6051.6
.2 COUNT( )
This function counts the number of rows in a given column.
If you specify the COLUMN name in parenthesis of function, then this function returns rows where
COLUMN is notnull.
If you specify the asterisk (*), this function returns all rows, including duplicates and nulls.
3. MAX( )
This function returns the maximum value from a given column or expression.
4. MIN( )
This function returns the minimum value from a given column or expression.
5. SUM( )
This function returns the sum of values in given column or expression.
Output
SUM(SAL)
30258
The GROUP BY clause combines all those records(row) that have identical values in a particular field(column) or a
group offields(columns).
GROUPING can be done by a column name, or with aggregate functions in which case the aggregate produces a
value foreach group.
Table : EMPL
EMPNO ENAME JOB SAL DEPTNO
8369 SMITH CLERK 2985 10
8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
8698 BINA MANAGER 5643 20
NESTED GROUP
- To create a group within a group i.e., nested group, you need to specify multiplefields in the GROUP BY
expression.
e.g. To group records job wise within Deptno wise, you need to issue a query statement like :
- The HAVING clause places conditions on groups in contrast to WHERE clause that places condition on
individualrows. While WHERE conditions cannot include aggregate functions, HAVING conditions can do
so.
- e.g. To display the jobs where the number of employees is less than 2,
- SELECT JOB, COUNT(*) FROM EMPL GROUP BY JOB
HAVING COUNT(*) < 2 ;
Output
JOB COUNT(*)
CLERK 1
MANAGER 1
MySQL FUNCTIONS
Types of MySQL functions : String Functions , Maths Functions and Date & Time Functions.
Table : EMPL
EMPNO ENAME JOB SAL DEPTNO
8369 SMITH CLERK 2985 10
8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
8698 BINA MANAGER 5643 20
8912 SUR NULL 3000 10
STRING FUNCTIONS
Output
CONCAT(EMPNO , ENAME)
8369SMITH
8912SUR
2. LOWER( ) / LCASE( ) - Returns the argument in
lowercase.Syntax : LOWER(Column
name)
e.g.
SELECT LOWER(ENAME) FROM EMPL ;
Output
LOWER(ENAME)
smith
anya
amir
bina
sur
e.g.
SELECT UPPER(ENAME) FROM EMPL ;
Output
UPPER(ENAME)
SMITH
ANYA
AMIR
BINA
SUR
4. SUBSTRING( ) / SUBSTR( ) – Returns the substring as specified.
Syntax : SUBSTR(Column name, m , n), where m specifies starting index and n specifies number of
charactersfrom the starting index m.
e.g.
SELECT SUBSTR(ENAME,2,2) FROM EMPL WHERE DEPTNO=20;
Output
SUBSTR(ENAME,2,2)
NY
IN
Output
LENGTH(ENAME)
5
4
4
4
3
9. LEFT( ) – Returns the leftmost numberof characters as specified.
e.g. SELECT LEFT(‘CORPORATE FLOOR’ , 3) ;
Output
LEFT(‘CORPORATE FLOOR’, 3)
COR
NUMERIC FUNCTIONS
These functions accept numeric values and after performing the operation, return numeric value.
1. MOD( ) – Returns the remainder of given two numbers. e.g. SELECT MOD(11 , 4);
Output
MOD(11, 4 )
3
2. POW( ) / POWER( ) - This function returns mn i.e , a numberm raised to the nth power.
e.g. SELECT POWER(3,2) ;
Output
POWER(3, 2 )
9
e.g. 2. SELECT ROUND(15.193 , -1); - This will convert the number to nearest ten’s .
Output
ROUND(15.193 , -1)
20
Output
TRUNCATE(15.79 , 1)
15.7
E.g. 2. SELECT TRUNCATE(15.79 , -1); - This command truncate value 15.79 to nearest ten’s place.
Output
TRUNCATE(15.79 , -1)
10
DATE AND TIME FUNCTIONS
Date functions operate on values of the DATE datatype.
2. DATE( ) – This function extracts the date part from a date. E.g.
SELECT DATE( ‘2016-02-09’) ;
Output
DATE( ‘2016-02-09’)
09
6. DAYOFMONTH( ) – This function returns the day of month. Returns value in range of 1 to 31.
E.g. SELECT DAYOFMONTH( ‘2016-12-14’) ;
Output
DAYOFMONTH( ‘2016-12-14’)
14
7. DAYOFWEEK( ) – This function returns the day of week. Return the weekdayindex for date.
(1=Sunday,2=Monday,……., 7=Saturday)
SELECT DAYOFWEEK( ‘2016-12-14’) ;
Output
DAYOFWEEK( ‘2016-12-14’)
4
8. DAYOFYEAR( ) – This function returns the day of the year. Returns the value between 1 and
366. E.g.SELECT DAYOFYEAR(‘2016-02-04) ;
Output
DAYOFYEAR( ‘2016-02-04’)
35
10. SYSDATE( ) – It also returns the current date but it return the time at which SYSDATE( ) executes. It differs
from thebehavior for NOW( ), which returns a constant time that indicates the time at which the statement
began to execute.
e.g. SELECT SYSDATE( ) ;
JOINS
- A join is a query that combines rows from two or more tables. In a join- query,
more thanone table are listed in FROM clause.
Table : empl
Table : dept
This query will give you the Cartesian product i.e. all possible concatenations are formed of
all rowsof both the tables EMPL and DEPT. Such an operation is also known as Unrestricted
Join. It returns n1 x n2 rows where n1 is number of rows in first table and n2 is number of
rows in second table.
EQUI-JOIN
- The join in which columns are compared for equality, is called Equi- Join. In equi-
join, all thecolumns from joining table appear in the output even if they are
identical.
e.g. SELECT * FROM empl, dept
WHERE empl.deptno = dept.deptno ;
deptno column is appearing twice in output.
Q: with reference to empl and dept table, find the location of employee SMITH.
ename column is present in empl and loc column is present in dept. In order to obtain the result, we
have to join two tables.
QUALIFIED NAMES
Did you notice that in all the WHERE conditions of join queries given so far, the field(column) names
are given as: <tablename>.<columnname>
This type of field names are called qualified field names. Qualified field names are very useful in
identifying a field if the two joining tables have fields with same time. For example, if we say deptno
field from joining tables empl and dept, you’ll definitely ask- deptno field of which table ? To avoid
such an ambiguity, the qualified field names are used.
TABLE ALIAS
- A table alias is a temporary label given along with table name in FROM clause.
e.g.
SELECT E.DEPTNO,
DNAME,EMPNO,ENAME,JOB,SALFROM
EMPL E, DEPT D
WHERE E.DEPTNO =
D.DEPTNOORDER BY
E.DEPTNO;
In above command table alias for EMPL table is E and for DEPT table , alias is D.
NATURAL JOIN
By default, the results of an equijoin contain two identical columns. One of the two
identical columns can be eliminated by restating the query. This result is called a Natural join.
empl.* means select all columns from empl table. This thing can be used with any table.
LEFT JOIN
- You can use LEFT JOIN clause in SELECT to produce left join i.e.
- When using LEFT JOIN all rows from the first table will be returned whether there are
matches in the second table or not. For unmatched rows of first table, NULL is shown
in columns of second table.
S1 S2
Roll_no Name Roll_no Class
1 A 2 III
2 B 4 IX
3 C 1 IV
4 D 3 V
5 E 7 I
6 F 8 II
SELECT S1.ROLL_NO, NAME,CLASS
FROM S1 LEFT JOIN S2 ON S1.ROLL_NO=S2.ROLL_NO;
RIGHT JOIN
- It works just like LEFT JOIN but with table order reversed. All rows from the second
table are going to be returned whether or not there are matches in the first table.
- You can use RIGHT JOIN in SELECT to produce right join i.e.
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",database="student",cha
rset="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)
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)
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)
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)
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)
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)
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",charset="utf8")
cur = cn.cursor()
print('Welcome to student Details Updation screen... ')
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
## RECORD UPDATED ##