0% found this document useful (0 votes)
26 views

How It Is How?

The document is a computer science practical record submitted by a student named Aayush Naveen kasaudhan of class XII to their teacher Mr. Sarman Singh. It contains expressions of gratitude to the teacher and principal for their support and guidance. It also states that the practical was completed to gain knowledge and fulfill examination requirements. The record contains the signature of the teacher, principal, and external examiner certifying the completion of the practical assignments.

Uploaded by

Aayush Naveen
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

How It Is How?

The document is a computer science practical record submitted by a student named Aayush Naveen kasaudhan of class XII to their teacher Mr. Sarman Singh. It contains expressions of gratitude to the teacher and principal for their support and guidance. It also states that the practical was completed to gain knowledge and fulfill examination requirements. The record contains the signature of the teacher, principal, and external examiner certifying the completion of the practical assignments.

Uploaded by

Aayush Naveen
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

SHAHEED PATH, LUCKNOW

COMPUTER SCIENCE
PRACTICAL
CLASS : XII
RECORD
SESSION : 2022 - 23

Submitted To: Submitted By:


Mr. Sarman Singh Aayush Naveen
kasaudhan
XII - A
(20 22- 23)
Roll no.
I would like to express my special thanks of gratitude to
our teacher Mr. Sarman Singh PGT (COMPUTER
SCIENCE), for his vital support, guidance, and
encouragement – without which this practical would
not have come forth.

We would also like to express our gratitude to our


principal Mrs. Poonam Kochitty and our school Seth
Anandram Jaipuria School, Lucknow for giving us
this opportunity to make this project.

I am making this practical file not only to


increase marks but also to gain knowledge.

THANKS AGAIN TO ALL WHO HELPED


ME.
SHAHEED PATH, LUCKNOW

This is to certify that Aayush Naveen


kasaudhan, student of class XII - Seth
Anandram Jaipuria School has
successfully completed the project
during the academic year 20 22-23
towards partial fulfillment of
Computer Science examination
conducted by CBSE.

Teacher's Signature Principal's Signature External Examiner's


Signature
XII CS – PRACTICAL ASSIGNMENTS
S.No. Description of Assignment Sign
1. Read a text file line by line and display each word separated by a #.
2. Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.
3. Create a binary file with name and roll number. Search for a given roll
number and display the name, if not found display appropriate message.
4. Create a binary file with name and roll number. Search for a given roll
number and display the name, if not found display appropriate message.
5. Create a binary file with roll number, name and marks. Input a roll number
and update the marks.
6. Write a random number generator that generates random numbers between 1
and 6 (simulates a dice).
7. Write a random number generator that generates random numbers between 1
and 6 (simulates a dice).
8. Write a Python program to implement a stack using list (PUSH & POP
Operation on Stack).
9. 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.
10. 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.
11. Create a table and insert data. Implement all SQL commands on the table.
12. Integrate MySQL with Python by importing the MySQL module and add
records of student
and display all the record.
13. 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.
14. Integrate SQL with Python by importing the MySQL module to search a
student using
rollno, delete the record.
15. Integrate SQL with Python by importing the MySQL module to search a
student using
rollno, update the record.
Assignment 1:
Read a text file line by line and display each word separated by a #.
Ans:

f=open("program1.txt","r")
t=f.readlines()
for i in t:
a=i.split(" ")
for c in a:
print(c,end="#")
f.close()

Output is:
Python#has#a#simple#syntax#similar#to#the#English#language.
#Python#has#syntax#that#allows#developers#to#write#programs#with#fewer#lines#than#some#othe
r#programming#languages.
#Python#runs#on#an#interpreter#system,#meaning#that#code#can#be#executed#as#soon#as#it#is#wr
itten.#

Assignment 2:
Read a text file and display the number of vowels/consonants/uppercase/lowercase characters in
the file.
Ans.

f=open("program1.txt","r")
a=f.read()
vowel=[]
consonant=[]
upper=[]
lower=[]
for i in a:
if
i.isalpha():
if i.isupper():
upper.append(i)
elif i.islower():
lower.append(i)
for i in a:
if i.isalpha():
if i in
["a","e","i","o","u",'
A','E','I','O','U']:
vowel.append(i)
else:
print(a)
print("No. of vowels= ",len(vowel))
print("No. of consonants= ", len(consonant))
print("No. of uppercase characters= ",len(upper))
print("No. of lowercase characters= ",len(lower))
f.close()

Output is:
Python has a simple syntax similar to the
English language.
Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is written.
No. of vowels= 78
No. of consonants= 146
No. of uppercase characters= 4
No. of lowercase characters= 220

Assignment 3:
Remove all the lines that contain the character “a” in a file and write it to another file.
Ans.

f = open("program3.txt","r")
new = open("New.txt","w")
b = f.readlines()
for i in b:
if "a" not in i:
new.write(i)
f.close()
new.close()
r = open("New.txt","r")
print(r.read())
r.close()

Output is:

Nursery Rhyme

Assignment 4:
Create a binary file with name and roll number. Search for a given roll number and display the
name, if not found display appropriate message.
Ans.
import pickle
f=open("program4.dat", "wb")
info=[[1,"Will"],[2,"Mike"],[3,"Dustin"],[4,"Lucas"],[5,"Eleven"],[6,"Max"]]
pickle.dump(info,f)
f.close()
r=open("program4.dat","rb")
result=pickle.load(r)
lst=[]
for i in result:
lst.append(i[0])
n=int(input("Enter the roll no."))
if n in lst:
for i in result:
if i[0]==n:
print("Name is:\n",i[1])
elif n not in lst:
print("This roll no. cannot be found.")
r.close()

Ouput is:

Enter the roll


no.5 Name is:
Eleven

Assignment 5:
Create a binary file with roll number, name and marks. Input a roll number and update the marks.

Ans.

import pickle
f=open("student.dat","wb")
while True:
name = input("Enter name ")
roll = int(input("Enter roll no. "))
marks = int(input("Enter marks
"))
table = [name, roll, marks]
pickle.dump(table,f)
a = input("Do you want to enter more data? (Y/N)")
if a in "Nn":
break
f.close()
r=
try:
while True:
e = pickle.load(r)
print(e)
except EOFError:
r.close()
g=
open("student.da
t", "rb+")
rn= int(input("enter the roll no you wish to update "))
try:
while True:
pos= g.tell()
e= pickle.load(g)
if e[1]==rn:
io=int(input("Enter the marks "))
e[2]=io
g.seek(pos)
pickle.dump(e,g)
except EOFError:
g.close()

Output is:

Enter name Radhika


Enter roll no. 1
Enter marks 99
Do you want to enter more data? (Y/N)y
Enter name Pika
Enter roll no. 2
Enter marks 98
Do you want to enter more data? (Y/N)n
['Radhika', 1, 99]
['Pika', 2, 98]
enter the roll no you wish to update 2
Enter the marks 80
Assignment 6:
Write a random number generator that generates random numbers between 1 and 6 (simulates a
dice).

Ans.
import random
while True:
print("Dice
thrown and
a=input("Do you want to continue? (Y/N)")
if a in "nN":
break

Output is:

Dice thrown and its a 2


Do you want to continue? (Y/N)y
Dice thrown and its a 4
Do you want to continue? (Y/N)y
Dice thrown and its a 3
Do you want to continue? (Y/N)n

Assignment 7:
Create a CSV file by entering user-id and password, read and search the password for given
userid.

Ans.

import csv
def write():
f=open("
data.csv"
, "w",
newline
="")
w=csv.writer(f)
w.writerow(["UserID", "Password"])
while True:
user = input("Enter user id ")
pd = input("Enter password ")
info = [user,pd]
w.writerow(info)
a = input("Do you want to enter more data? (Y/N)")
if a in "Nn":
break
f.close()

def read():
f=open("data.csv" , "r")
r=csv.reader(f)
for i in r:
print(i)

def update():
r=csv.reader(f
) for i in r:
if i[0]==a:
print(i[1])
f.close()

write()
read()
update()

Outp
ut is:

Enter
user id
Millie
Enter
passwor
d
ElevenJa
ne
Do you want to enter more data? (Y/N)y
Enter user id Mike
Enter password HelloFinn
Do you want to enter more data? (Y/N)y
Enter user id Suzie
Enter password PlancksConstant
Do you want to enter more data? (Y/N)n
['UserID', 'Password']
['Millie', 'ElevenJane']
Assignment
['Mike', 8:
'HelloFinn']
Write a Python
['Suzie', program to implement a stack using list .
'PlancksConstant']
Enter
Ans: the user ID you wish to search Suzie
PlancksConstant
def push(stack,elt):
stack.append(elt)
print("Element added")
print(stack)
def pop(stack):
if (stack==[]):
print("Underflow")
else:
print(stack.pop())
def peek(stack):
if stack==[]:
print("Stack is empty.")
else:
print("Element at top of the stack ", stack[-1])
def display(stack):
a=stack[::-1]
print(a)
a=eval(input("
Enter the data
(in the form of
list): "))
print("\n 1. Push an element \n 2. Pop an element \n 3. See the top element of \n 4.Display the elements
of stack")
while True:
n=int(input("Enter your choice"))
if n==1:
b=eval(input("Enter the
element to be inserted"))
push(a,b)
if n==2:
pop(a)
if n==3:
peek
(a)
if n==4:
display(a)
if n not in [1,2,3,4]:
print("Bye")
break

Output is:
Enter the data (in the
form of list):
[1,2,3,'abc']

1. Push an element
2. Pop an element
3.See the top element of
4.Display the elements of stack
Enter your choice1
Enter the element to be
inserted'rads'
Element added
[1, 2, 3, 'abc', 'rads']
Enter your choice3
Element at top of the stack rads
Enter your choice4
['rads', 'abc', 3, 2, 1]
Enter your choice2
rads
Enter your choice0
Bye
Assignment 9:
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('By
e') 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 10:
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
>>>
Assignment 11: 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
employee( ECODE
TABLE
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);
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000

In order to insert another row in EMPLOYEE table , we write again INSERT


command :INSERT INTO employee
VALUES(1002 , ‘Akash’ , ‘M’ , ‘A1’ , 35000);

ECODE ENAME GENDER GRADE GROSS


1001 Ravi M E4 50000
1002 Akash M A1 35000

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 :

INSERT INTO EMPLOYEE


VALUES (1004 , NULL , ‘M’ , ‘B2’ , 38965 ) ;
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 NULL M B2 38965

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 atable, SELECT command 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

SELECT * FROM Employee ;

5. SELECTING PARTICULAR COLUMNS


EMPLOYEE

ECODE ENAME GENDER GRADE GROSS


1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 Neela F B2 38965
1005 Sunny M A2 30000
1006 Ruby F A1 45000
1009 Neema F A2 52000
- A particular column from a table can be selected by specifying column-names with SELECT command.
E.g. in above table, if we want to select ECODE and ENAME column, then command is:
SELECT ECODE, ENAME

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

WHERE GENDER = ‘F’;

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,
GENDER
SELECT GENDERM FROM EMPLOYEE;
M
F
M
F
F

SELECT DISTINCT(GENDER) FROM EMPLOYEE;

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, command is : 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 foroutput
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;

10. 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 lower value 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
11. 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 operator finds 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

12. CONDITION BASED ON PATTERN MATCHES


- LIKE operator is used for pattern matching in SQL. Patterns are described using two special wildcard
characters:

1. percent (%) – The % character matches any substring.


2. underscore (_) – The _ character matches any character.

e.g. to display names of employee whose name starts with R in EMPLOYEE table, the command
is: SELECT ENAME FROM EMPLOYEE

WHERE ENAME LIKE ‘R%’;

Output will be:


ENAME
Ravi
Ruby

e.g., to display details of employee whose second character in


name is ‘e’.SELECT *
FROM EMPLOYEE

WHERE ENAME LIKE ‘_e%’;

Output will be:


ECODE ENAME GENDER GRADE GROSS
1004 Neela F B2 38965
1009 Neema F A2 52000

e.g., to display details of employee whose name ends


with ‘y’.SELECT *
FROM EMPLOYEE

WHERE ENAME LIKE ‘%y’;

Output will be:


ECODE ENAME GENDER GRADE GROSS
1005 Sunny M A2 30000
1006 Ruby F A1 45000

13. 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

WHERE GROSS IS NULL;

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

WHERE Marks IS NULL;

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.

The ORDER BY clause is used as:


SELECT <column name> ,
<column name>….FROM
<tablename> WHERE <condition>
ORDER BY <column name> ;
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

15. MODIFYING DATA IN TABLES


you can modify data in tables using UPDATE command of SQL. The UPDATE command specifies the rows to be
changedusing the WHERE clause, and the new data using the SET keyword.

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 ;

16. UPDATING MORE THAN ONE COLUMNS


e.g. to update the salary to 58000 and grade to B2 for those employee whose employee code is 1001.
UPDATE EMPLOYEE

SET GROSS = 58000, GRADE=’B2’


WHERE ECODE = 1009 ;

OTHER EXAMPLES
Increase the salary of each employee by 1000 in the EMPLOYEE table.
UPDATE EMPLOYEE

SET GROSS = GROSS +100 ;


Double the salary of employees having grade as ‘A1’ or ‘A2’ .
UPDATE EMPLOYEE
SET GROSS = GROSS * 2 ;
WHERE GRADE=’A1’ OR GRADE=’A2’ ;

Change the grade to ‘A2’ for those employees whose employee code is 1004 and name is Neela.
UPDATE EMPLOYEE

SET GRADE=’A2’

WHERE ECODE=1004 AND GRADE=’NEELA’ ;

17. DELETING DATA FROM TABLES


To delete some data from tables, DELETE command is used. The DELETE command removes rows from a
table.
Thesyntax of DELETE command is:

DELETE FROM <tablename>

WHERE <condition> ;

For example, to remove the details of those employee from EMPLOYEE table whose grade is A1.
DELETE FROM EMPLOYEE

WHERE GRADE =’A1’ ;

18. TO DELETE ALL THE CONTENTS FROM A TABLE


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.

19. DROPPING TABLES


The DROP TABLE command lets you drop a table from the database.

e.g. to drop a table employee, we need to write :


DROP TABLE employee ;

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.

20. ALTER TABLE COMMAND


The ALTER TABLE command is used to change definitions of existing tables.(adding columns,deleting columns
etc.). TheALTER TABLE command is used for :
20. adding columnsto a table
21. Modifying column-definitions of a table.
22. Deleting columns of a table.
23. Adding constraints to table.
24. Enabling/Disabling constraints.

21. ADDING COLUMNS TO TABLE


To add a column to a table this command is used,
e.g. to add a new column ADDRESS to the EMPLOYEE table, we can write command as :
ALTER TABLE EMPLOYEE

ADD ADDRESS VARCHAR(50);


A new column by the name ADDRESS will be added to the table, where
each row will contain NULL value forthe new column.
ECODE ENAME GENDER GRADE GROSS ADDRESS
1001 Ravi M E4 50000 NULL
1002 Akash M A1 35000 NULL
1004 Neela F B2 38965 NULL
1005 Sunny M A2 30000 NULL
1006 Ruby F A1 45000 NULL
1009 Neema F A2 52000 NULL
However if you specify NOT NULL constraint while adding a new column, MySQL adds the new column with the
defaultvalue of that datatype e.g. for INT type it will add 0 , for CHAR types, it will add a space, and so on.

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) NOTNULL
) ; ALTER TABLE testtADD col6 VARCHAR(3);
(iv
)
22. MODIFYING COLUMNS

In table EMPLOYEE, change the column GROSS to SALARY.

ALTER TABLE EMPLOYEE

CHANGE GROSS SALARY INTEGER;

In table EMPLOYEE , change the column ENAME to EM_NAME and data type from
VARCHAR(20) toVARCHAR(30).

ALTER TABLE EMPLOYEE

CHANGE ENAME EM_NAME VARCHAR(30);

In table EMPLOYEE , change the datatype of GRADE column from CHAR(2) to VARCHAR(2).

ALTER TABLE EMPLOYEE

MODIFY GRADE VARCHAR(2);

23. DELETING COLUMNS

To delete a column from a table, the ALTER TABLE command takes the following form :

ALTER TABLE <table name>


DROP <column name>;

e.g. to delete column GRADE from table EMPLOYEE, we will write :


ALTER TABLE EMPLOYEE

DROP GRADE ;

24. ADDING/REMOVING CONSTRAINTS TO A TABLE


ALTER TABLE statement can be used to add constraints to your existing table.
e.g. to add PRIMARY KEY constraint on column ECODE of table EMPLOYEE , the command
is :
ALTER TABLE EMPLOYEE

ADD PRIMARY KEY (ECODE) ;

25. REMOVING CONSTRAINTS


- To remove foreign key constraint from a table, we use ALTERTABLE command as :
ALTER TABLE <table name>

DROP FOREIGN KEY ;


AGGREGATE / GROUP FUNCTIONS
Aggregate / Group functions work upon groups of rows , rather than on single row, and return one single
output.Different aggregate functions are : COUNT( ) , AVG( ) , MIN( ) , MAX( ) , SUM ( )

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

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.

e.g. SELECT COUNT(*)FROM EMPL ;


Output
COUNT(*)
5

e.g.2 SELECT COUNT(JOB)FROM


EMPL ;
Output COUNT(JOB)
4

3. MAX( )
This
functi
on
return
s the
maxi
mum
value MAX(SAL)
from a 9870
given
colum
n or
4. MIN( )
This
functi
on
return
s the
minim MIN(SAL)
um 2985
value
from
5. SUM( )
a
This
given
functio
colum
n
n or
return
expres
s the
sion.
sum of
values SUM(SAL)
e.g.
in
SELEC 30258
given
Tcolum
GROUPING
MIN(S
n or RESULT – GROUP BY
AL)FR
expres
TheOM GROUP BY clause combines all those records(row) that have identical values in a particular field(column) or a
sion.
group
EMPL offields(columns).
;
GROUPING can be done by a column name, or with aggregate functions in which case the aggregate produces a
e.g.
valueOut
foreach group.
SELEC
Tput Table : EMPL
SUM(S
AL)FR EMPNO ENAME JOB SAL DEPTNO
OM 8369 SMITH CLERK 2985 10
EMPL ; 8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
Out 8698 BINA MANAGER 5643 20
put
e.g. Calculate the number of employees in each grade.

SELECT JOB, COUNT(*)FROM EMPL


GROUP BY JOB ;
Output

JOB COUNT(*)
CLERK 1
SALESMAN 2
MANAGER 1

e.g.2. Calculate the sum of salary for each


department.
SELECT DEPTNO ,
SUM(SAL)FROM
EMPL
GROUP BY
DEPTNO ;
DEPTNO SUM(SAL)
Output 10 2985
20 15513
30 8760
e.g.3. find the average salary of each
department.
Sol: select avg(sal)FROM EMPL
GROUP BY DEPTNO ;

NESTED GROUP
- To create a group within agroup i.e., nested group, you need to specify multiple fields in the
GROUP BY expression.
e.g. To group records job wise within Deptno wise, you need to issue a query statement like :

SELECT DEPTNO , JOB ,


COUNT(EMPNO)FROM
EMPL GROUP BY DEPTNO ,
JOB ;
Output
DEPTNO JOB COUNT(EMPNO)
10 CLERK 1
20 SALESMAN 1
20 MANAGER 1
30 SALESMAN 1

PLACING CONDITION ON GROUPS – HAVING CLAUSE

- 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

1. CONCAT( ) - Returns the Concatenated String.


Syntax : CONCAT(Column1 , Column2 , Column3, …….)
e.g. SELECT CONCAT(EMPNO , ENAME) FROM EMPL
WHEREDEPTNO=10;

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

3. UPPER( ) / UCASE( ) - Returns the argument in


uppercase.Syntax : UPPER(Column
name)

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

SELECT SUBSTR(JOB,-2,2) FROMEMPL WHERE


DEPTNO=20;
Output

SUBSTR(JOB,-4,2)
SM
AG

5. LTRIM( ) – Removes leading spaces.


e.g. SELECT
LTRIM(‘ RDBMS MySQL’) ;
Output LTRIM(‘ RDBMS MySQL’)
RDBMS MySQL
6. RTRIM( ) – Removes trailing
spaces. RDBMS MySQL ’) ;
e.g. SELECT
Output
RTRIM(‘
RTRIM(‘ RDBMS MySQL’)
RDBMS MySQL

7. TRIM( ) – Removes trailing and leading


spaces. RDBMS MySQL ’) ;
e.g.

TRIM(‘
SELECT RDBMS MySQL’)
TRIM(‘
RDBMS MySQL
Output
8. LENGTH() – Returns the length of a string. e.g.
SELECT
LENGTH(“CANDID”) ;
Output LENGTH(“CANDID”)
6

e.g.2.
SELECT LENGTH(ENAME) FROM
EMPL;
Output LENGTH(ENAME)
5
4
4
4
3
9. LEFT( ) – Returns the leftmost number of characters as
specified.
e.g. SELECT LEFT(‘CORPORATE
FLOOR’ , 3) ;
LEFT(‘CORPORATE FLOOR’, 3)
Output COR

10. RIGHT( ) – Returns the rightmost number of characters as


specified.
e.g. SELECT RIGHT(‘CORPORATE
FLOOR’ , 3) ;
RIGHT(‘CORPORATE FLOOR’, 3)
Output OOR

11. MID( ) – This function is same as SUBSTRING( ) / SUBSTR( )


function. E.g.SELECT MID(“ABCDEF” , 2 ,
4) ;
Output MID(“ABCDEF” , 2 , 4 )
BCDE

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 returnsmn i.e , a number m raised to the nth
power.
e.g. SELECT POWER(3,2) ;
Output POWER(3, 2 )
9

3. ROUND() – This function returns a number rounded off as per given


specifications.
e.g. ROUND(15.193 , 1) ;
Output ROUND(15.193 , 1)
15.2

e.g. SELECT ROUND(15.193 , -1); - This will convert the number to nearest
2. ten’s .

Output
ROUND(15.193 , -1)
20
4. SIGN( ) – This function returns sign of a given
number.
If number is negative, the function
returns -1.If number is positive, the
function returns 1. If number is
zero, the function returns 0.

e.g. SELECT SIGN(-15) ;


Output SIGN(-15)
-1

e.g.2 SELECT
OutputSIGN(20) ;
SIGN(20)
1

5. SQRT( ) – This function returns the square root of a


given number. E.g.SELECT SQRT(25) ;
Output
SQRT(25)
5

6. TRUNCATE( ) – This function returns a number with some


digits truncated. E.g.SELECT TRUNCATE(15.79 ,
1) ;

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.

1. CURDATE( ) / CURRENT_DATE( ) – This function returns the current date.E.g.


SELECT CURDATE( ) ;
Output
CURDATE( )
2016-12-13

2. DATE( ) – This function extractsthe date part from a date.


E.g.
SELECT DATE( ‘2016-02-09’) ;
Output DATE( ‘2016-02-09’)
09

3. MONTH( ) – This function returns the month from the date


passed. E.g.SELECT MONTH( ‘2016-02-
09’) ;
Output MONTH( ‘2016-02-09’)
02

4. YEAR() – This function returns the year part of a date.


E.g.
SELECT YEAR( ‘2016-02-09’) ;
Output YEAR( ‘2016-02-09’)
2016

5. DAYNAME( ) – This function returns the name of weekday.


E.g.
SELECT DAYNAME( ‘2016-02-09’) ;
Output DAYNAME( ‘2016-12-14’)
Wednesday

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 week day index 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

9. NOW( ) – This function returns the current date and time.


It returns a constant time that indicates the time at which the statement began to execute.

e.g. SELECT NOW( );

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

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

Table : dept

DEPTNO DNAME LOC


10 ACCOUNTING NEW DELHI
20 RESEARCH CHENNAI
30 SALES KOLKATA
40 OPERATIONS MUMBAI

CARTESIAN PRODUCT/UNRESTRICTED JOIN/CROSS JOIN


- Consider the following
query : SELECT * FROM EMPL,
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.

SELECT ENAME, LOC


FROM EMPL, DEPT
WHERE
EMPL.DEPTNO =
DEPT.DEPTNO AND
ENAME=’SMITH’;

Q: Display details like department number, department name,


employee number, employeename, job and salary. And order the
rows by department number.

SELECT EMPL.deptno, dname,empno,ename,job,sal


FROM EMPL,DEPT
WHERE EMPL.DEPTNO=DEPT.DEPTNO
ORDER BY EMPL.DEPTNO;

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.

Q: Display details like department number, department name,


employee number, employee name, job and salary. And order
the rows by employee number with department number. These
details should be only for employees earning atleast Rs. 6000 and
of SALESdepartment.

SELECT E.DEPTNO, DNAME,EMPNO, ENAME, JOB, SALFROM EMPL E, DEPT D


WHERE E.DEPTNO = D.DEPTNOAND DNAME=’SALES’ AND SAL>=6000
ORDER BY E.DEPTNO;

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.

e.g. SELECT empl.*, dname, locFROM


empl,dept WHERE empl.deptno =
dept.deptno ;

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.

e.g SELECT S1.ROLL_NO, NAME,CLASS


FROM S1 RIGHT JOIN S2 ON
S1.ROLL_NO=S2.ROLL_NO;
Assignment 12:
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.connecto
r

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.exe
cute("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():
runAg
n=
input("\
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:
")

runAgai

n() Output

is:
<mysql.c
onnector.co
nnection.M
ySQLConne
ction
object at
0x0227211
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)

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)
(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 13:
Integrate MySQL with Python by importing the MySQL module to search student
using roll no, name, age, class and if present in table display the record, if not
display appropriate method.
Ans:
import os
import platform
import
mysql.connecto
r

mydb=mysql.co
nnector.connect
(host="localhos
t",\
user="root",\
passwd="root",\
database="stude
nt",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:
")

runAgai

n() Output

is:
<mysql.c
onnector.co
nnection.M
ySQLConne
ction object
at
0x022720F
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 : 1
Enter roll no : 8
The Students details are as follows :
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 :
6. Roll
7. Name
8. Age
9. Class
10.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 :
11.Roll
12.Name
13.Age
14.Class
15.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 14:
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.connecto
r

mydb=mysql.co
nnector.connect
(host="localhos
t",\
user="root",\
passwd="root",\
database="stude
nt",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
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 15:
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... ')

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