0% found this document useful (0 votes)
19 views47 pages

Tesara lond

3=D

Uploaded by

aquemontt
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)
19 views47 pages

Tesara lond

3=D

Uploaded by

aquemontt
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
You are on page 1/ 47

SARVODAYA KANYA

VIDYALAYA,
KHAJOORI KHAS

COMPUTER SCIENCE (083)


PRACTICAL FILE
2024-2025

SUBMITTED BY:
CLASS AND SECTION : XII
ROLL NUMBER:
INDEX
PAGE TEACHER’S
S.NO PROGRAM
NO. SIGN
Write a program in python to enter two numbers and print the
1.
arithmetic operation like +,-,*,/,//,% and ** using functions.

Write a program in python to find the factorial of a number


2.
using function.

Write a program in python to enter the number of terms and to


3.
print the Fibonacci series.

Write a Program in python to accept a string and to check


4.
whether it is a palindrome or not.

Write a program in python to display those string which starts


5.
with “A” from a given list.

6. Write a program in python to read a file line by line and print it.

Write a program in python to read a file line by line and display


7.
each word separated by a #.

Write a program in python to read a text file and display the


8. number of vowels/Consonants/ uppercase and lowercase
characters in the file.

Write a program in python to remove all the lines that contain


9.
the character ‘a’ in a file and write it to another file.

Write a program in python to find the occurrence of a given


10.
word/string in the file.

Write a program in python to create a binary file with name


11. and roll no. Search for a given roll number and display the
name if not found display appropriate message.

Write a program in python to create a binary file with name


12. and roll no. and marks. Input a roll number and update the
marks if roll no not found display appropriate message.

Write a program in python to create a CSV file with details of 5


13.
students.

14. Write a program in python to read a CSV file and print data.

Write a random number generator that generates random


15.
number between 1 and 6(simulate a dice)

Write a menu based program to perform the operation on


16.
stack in python.

Write a menu based program for maintaining books details like


17.
bcode, btitle and price using stacks in python.
18. SQL queries set-1

19. SQL queries set-2

20. SQL queries set-3

21. SQL queries set-4

22. SQL queries set-5


Write a program in python using mysql python connectivity to create
23.
table student, insert data into student table and display record.

Write a program using mysql python connectivity to search the


24. record of a student using ID from student table.

Write a program using python mysql connectivity to update subject


25.
of a student.

Write a program using python mysql connectivity to delete a record


26. from student table.
1. Write a program in python to enter two numbers and print the arithmetic
operation like +,-,*,/,//,% and ** using functions.
Code:
def add(a,b):
res=a+b
return res
def sub(a,b):
res=a-b
return res
def mul(a,b):
res=a*b
return res
def div(a,b):
res=a/b
return res
def fdiv(a,b):
res=a//b
return res
def rem(a,b):
res=a%b
return res
def power(a,b):
res=a**b
return res
num1=int(input("Enter the first number : "))
num2=int(input("Enter the Second number : "))
print("The addition of numbers is = ",add(num1,num2))
print("The subtraction of numbers is = ",sub(num1,num2))
print("The multiplication of numbers is = ",mul(num1,num2))
print("The division of numbers is = ",div(num1,num2))
print("The floor division of numbers is = ",fdiv(num1,num2))
print("The remainder of number is = ",rem(num1,num2))
print("The Exponent of number is = ",power(num1,num2))

Output:
Enter the first number : 5
Enter the Second number : 2
The addition of numbers is = 7
The subtraction of numbers is = 3
The multiplication of numbers is = 10
The division of numbers is = 2.5
The floor division of numbers is = 2
The remainder of number is = 1
The Exponent of number is = 25
2. Write a program in python to find the factorial of a number using function.
CODE:
def fact(n):
f=1
while(n>0):
f=f*n
n=n-1
return f

n=int(input("Enter a number to find the factorial : "))


if(n<0):
print("Factorial of negative number is not possible")
elif(n==0):
print("Factorial of zero is 1")
else:
print("Factorial of ",n,"is ",fact(n))
OUTPUT:
Enter a number to find the factorial : 5
Factorial of 5 is 120
Enter a number to find the factorial : 0
Factorial of zero is 1
Enter a number to find the factorial : -1
Factorial of negative number is not possible

3. Write a program in python to enter the number of terms and to print the
Fibonacci series.
CODE:
def fibonacci(n):
n1,n2=0,1
count=0
while(count<nterms):
print(n1)
nth=n1+n2
n1=n2
n2=nth
count=count+1
nterms=int(input("Enter the numbers of terms to print fibbonaci series : "))
if nterms<=0:
print("Please enter a positive value ")
else:
print(nterms," terms of Fibonacci series : ")
fibonacci(nterms)
OUTPUT:
Enter the numbers of terms to print fibbonaci series : 6
6 terms of Fibonacci series :
0
1
1
2
3
5

4. Write a Program in python to accept a string and to check whether it is a


palindrome or not.
CODE:
str=input("Enter the string : ")
l=len(str)
p=l-1
index=0
while(index<p):
if(str[index]==str[p]):
index=index+1
p=p-1
else:
print("String is not a palindrome")
break
else:
print("String is palindrome")
OUTPUT:
5. Write a program in python to display those string which starts with “A” from a
given list.
CODE:
L=['RAVI','ALISHA','append','Truth']
count=0
for i in L:
if i[0] in ('a','A'):
count=count+1
print(i)
print("String starting with A appearing",count,"times.")
OUTPUT:
ALISHA
append
String starting with A appearing 2 times.
6.Write a program in python to read a file line by line and print it.
CODE:
f1=open("seven.txt","r")
count=0
for i in f1.readlines():
count+=1
print("Line",count,":",i)

OUTPUT:
7. Write a program in python to read a file line by line and display each word
separated by a #.
CODE:
f1=open("seven.txt","r")
for i in f1.readlines():
words=i.split()
for w in words:
print(w+"#",end='')
print()
f1.close()
OUTPUT:
8.Write a program in python to read a text file and display the number of
vowels/Consonants/ uppercase and lowercase characters in the file.
CODE:
f1=open("seven.txt","r")
vowels=0
consonants=0
uppercase=0
lowercase=0
v=['A','a','E','e','I','i','O','o','U','u']
str=f1.read()
print(str)
for i in str:
if i.islower():
lowercase+=1
elif i.isupper():
uppercase+=1

for j in str:
if j in v:
vowels+=1
else:
if j.isalpha():
consonants+=1
print("Lower case : ",lowercase)
print("Upper case : ",uppercase)
print("vowels : ",vowels)
print("consonants : ",consonants)

OUTPUT:
9. Write a program in python to remove all the lines that contain the character ‘a’ in
a file and write it to another file.
CODE:
file1=open('seven.txt')
file2=open('myfilenew.txt','w')
for line in file1:
if "a" not in line:
file2.write(line)
print("File copied sucessfully")
file1.close()
file2.close()

OUTPUT:
10.Write a program in python to find the occurrence of a given word/string in the
file.
CODE:
f1=open('seven.txt','r')
data=f1.read()
a=data.split()
str1=input("Enter the word to search : ")
count=0
for word in a:
if word==str1:
count=count+1
if count==0:
print("word not found")
else:
print("Word occurs ",count," times")

OUTPUT:
11.Write a program in python to create a binary file with name and roll no. Search
for a given roll number and display the name if not found display appropriate
message.
CODE:
import pickle
S=[]
f=open("stud.dat","wb")
c='y'
while c=='y' or c=='Y':
rno=int(input("Enter the roll no. of the student : "))
name=input("Enter the name of the student : ")
S.append([rno,name])
pickle.dump(S,f)
c=input("Do you want to add more?")
f.close()
f=open('stud.dat','rb')
student=[]
try:
while True:
student=pickle.load(f)
except EOFError:
f.close()
found=False
rno=int(input("Enter the roll no. of the student to be search: "))
for a in student:
if a[0]==rno:
print("Name is : ",a[1])
found=True

if found==False:
print("Student not found")

OUTPUT:
12.Write a program in python to create a binary file with name and roll no. and
marks. Input a roll number and update the marks if roll no not found display
appropriate message.
CODE:
import pickle
S=[]
f=open("stud1.dat","wb")
c='y'
while c=='y' or c=='Y':
rno=int(input("Enter the roll no. of the student : "))
name=input("Enter the name of the student : ")
marks=int(input("Enter the marks : "))
S.append([rno,name,marks])
pickle.dump(S,f)
c=input("Do you want to add more?")
f.close()
f=open('stud1.dat','rb')
student=[]
try:
while True:
student=pickle.load(f)
except EOFError:
f.close()
found=False
rno=int(input("Enter the roll no. of the student for updating marks: "))
for a in student:
if a[0]==rno:
print("Name is : ",a[1])
print("Current marks : ",a[2])
m=int(input("Enter new marks : "))
a[2]=m
print("Record Updated")
found=True

if found==False:
print("Roll no. not found")
OUTPUT:
13. Write a program in python to create a CSV file with details of 5 students.
CODE:
import csv
f=open("student.csv","w",newline="")
cw=csv.writer(f)
cw.writerow(['Rollno','Name','Marks'])
for i in range(5):
print("Student ",i+1," record : ")
rollno=int(input("Enter Roll No : "))
name=input("Enter name : ")
marks=float(input("Enter Marks : "))
sr=[rollno,name,marks]
cw.writerow(sr)
f.close()
print("File created successfully")
OUTPUT:
14. Write a program in python to read a CSV file and print data.
CODE:
import csv
f=open("student.csv","r")
cr=csv.reader(f)
print("Content of CSV file : ")
for data in cr:
print(data)

f.close()
OUTPUT:
15.Write a random number generator that generates random number between 1 and
6(simulate a dice)
import random
while True:
choice=input("Enter 'r' for rolling the dice or press any key to quit ")
if (choice.lower()!='r'):
break
n=random.randint(1,6)
print(n)

OUTPUT:
16.:- Write a menu based program to perform the operation on stack in
python.
Code:-
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"
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"
else:
top=len(S)-1
return S[top]
def Show(S):
if isEmpty(S):
print("Sorry No items in Stack ")
else:
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ')
t-=1
print()
# main begins here
S=[] #Stack
top=None
while True:
print("**** STACK DEMONSTRATION ******")
print("1. PUSH ")
print("2. POP")
print("3. PEEK")
print("4. SHOW STACK ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Push :"))
Push(S,val)
elif ch==2:
val = Pop(S)
if val=="Underflow":
print("Stack is Empty")
else:
print("\nDeleted Item was :",val)
elif ch==3:
val = Peek(S)
if val=="Underflow":
print("Stack Empty")
else:
print("Top Item :",val)
elif ch==4:
Show(S)
elif ch==0:
print("Bye")
else:
print("Invalid Choice")
17. Write a menu based program for maintaining books details like bcode, btitle and
price using stacks in python.
book=[]
def push():
bcode=input("Enter bcode:- ")
btitle=input("Enter btitle:- ")
price=input("Enter price:- ")
bk=(bcode,btitle,price)
book.append(bk)
def pop():
if(book==[]):
print("Underflow / Book Stack in empty")
else:
bcode,btitle,price=book.pop()
print("poped element is ")
print("bcode:- ",bcode," btitle:- ",btitle," price:- ",price)
def traverse():
if not (book==[]):
n=len(book)
for i in range(n-1,-1,-1):
print(book[i])
else:
print("Empty , No book to display")
while True:
print("Book Stall")
print("*"*40)
print("1. Push")
print("2. Pop")
print("3. Traversal")
print("4. Exit")
ch=int(input("Enter your choice:- "))
if(ch==1):
push()
elif(ch==2):
pop()
elif(ch==3):
traverse()
elif(ch==4):
print("End")
break
else:
print("Invalid choice")

OUTPUT:
18.Query Set 1: To write SQL Queries for the following questions based on the given table:-
Rollno Name Gender Age Dept DOA Fees
1 Arun M 24 Computer 1997-01-10 120
2 Ankit M 21 History 1998-03-24 200
3 Annu F 20 Hindi 1996-12-12 300
4 Mahesh M 19 NULL 1999-07-01 400
5 Ashok M 18 Hindi 1997-09-05 250
6 Mansi F 19 History 1997-06-27 300
7 Priya F 18 Computer 2023-06-27 210
8 Riya F 17 NULL 2023-02-17 200

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


mysql> CREATE DATABASE STUDENTS;
OUTPUT:- Query OK, 1 row affected (2.77 sec)

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

mysql> USE STUDENTS;


OUTPUT:- Database changed

c) Write a Query to create the above table called: Info

mysql> CREATE TABLE STU(Rollno int Primary key,Name varchar(10),Gender


varchar(3),Age int,Dept varchar(15),DOA date,Fees int);
OUTPUT:- Query OK, 0 rows affected (3.31 sec)

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

mysql> SHOW DATABASES;


+----------------------------+
| Database |
+----------------------------+
| information_schema |
| mysql |
| performance_schema |
| school |
| students |
| sys |
+----------------------------+
6 rows in set (0.00 sec)

e) Write a Query to List all the tables that exists in the current database
mysql> SHOW TABLES;
+-------------------------+
| Tables_in_students |
+-------------------------+
| stu |
+-------------------------+
1 row in set (0.29 sec)
19 Query Set 2: To write SQL Queries for the following questions based on the given table:-
Rollno Name Gender Age Dept DOA Fees
1 Arun M 24 Computer 1997-01-10 120
2 Ankit M 21 History 1998-03-24 200
3 Annu F 20 Hindi 1996-12-12 300
4 Mahesh M 19 NULL 1999-07-01 400
5 Ashok M 18 Hindi 1997-09-05 250
6 Mansi F 19 History 1997-06-27 300
7 Priya F 18 Computer 2023-06-27 210
8 Riya F 17 NULL 2023-02-17 200

a) Write a Query to insert all the rows of above table into Info table.
mysql> INSERT INTO STU VALUES (1,'Arun','M', 24,'COMPUTER','1997-01-10', 120);
Query OK, 1 row affected (3.45 sec)

mysql> INSERT INTO STU VALUES (2,'Ankit','M', 21,'HISTORY','1998-03-24', 200);


Query OK, 1 row affected (0.31 sec)

mysql> INSERT INTO STU VALUES (3,'Annu','F', 20,'HINDI','1996-12-12', 300);


Query OK, 1 row affected (0.42 sec)

mysql> INSERT INTO STU VALUES (4,'Mahesh','M', 19, NULL,'1999-07-01', 400);


Query OK, 1 row affected (0.10 sec)

mysql> INSERT INTO STU VALUES (5,'Ashok','M', 18,'HINDI','1997-06-27', 250);


Query OK, 1 row affected (0.23 sec)

mysql> INSERT INTO STU VALUES (6,'Mansi','F', 19,'HISTORY','1997-06-27', 300);


Query OK, 1 row affected (0.57 sec)

mysql> INSERT INTO STU VALUES(7,'Priya','F',18,'COMPUTER','2023-06-27',210);


Query OK, 1 row affected (0.25 sec)

mysql> INSERT INTO STU VALUES (8,'Riya','F', 17, NULL,'2023-02-17', 200);


Query OK, 1 row affected (0.15 sec)

a) Write a Query to display all the details of the Employees from the above table 'STU'.
mysql> SELECT * FROM STU;
Output:
+--------+---------+----------+------+--------------+--------------+------+
| Rollno| Name | Gender | Age | Dept | DOA | Fees |
+--------+---------+----------+------+--------------+---------------+------+
| 1 | Arun | M | 24 | COMPUTER | 1997-01-10 | 120 |
| 2 | Ankit | M | 21 | HISTORY | 1998-03-24 | 200 |
| 3 | Annu |F | 20 | HINDI | 1996-12-12 | 300 |
| 4 |Mahesh | M | 19 | NULL | 1999-07-01 | 400 |
| 5 | Ashok | M | 18 | HINDI | 1997-06-27 | 250 |
| 6 | Mansi | F | 19 | HISTORY | 1997-06-27 | 300 |
| 7 | Priya | F | 18 | COMPUTER | 2023-06-27 | 210 |
| 8 | Riya |F | 17 | NULL | 2023-02-17 | 200 |
+--------+---------+----------+------+---------------+-------------+--------+
8 rows in set (0.09 sec)

b) Write a query to Rollno, Name and Department of the students from STU table.

mysql> SELECT ROLLNO,NAME,DEPT FROM STU;


+----------+-----------+---------------+
| ROLLNO | NAME | DEPT |
+-----------+----------+---------------+
| 1 | Arun | COMPUTER|
| 2 | Ankit | HISTORY |
| 3 | Annu | HINDI |
| 4 | Mahesh| NULL |
| 5 | Ashok | HINDI |
| 6 | Mansi | HISTORY |
| 7 | Priya | COMPUTER|
| 8 | Riya | NULL |
+----------+-------- --+---------------+
8 rows in set (0.00 sec)

c) Write a Query to select distinct Department from STU table

mysql> select distinct(Dept) from stu;

+------------------+
| Dept |
+------------------+
| COMPUTER |
| HISTORY |
| HINDI |
| NULL |
+------------------+
4 rows in set (0.10 sec)

d) To show all information about students of history department.


mysql> select *from stu where Dept='HISTORY';

+--------+---------+----------+------+----------+---------------+------+
| Rollno | Name | Gender | Age | Dept | DOA | Fees |
+--------+---------+----------+------+-----------+---------------+------+
| 2 | Ankit | M | 21 | HISTORY | 1998-03-24 | 200 |
| 6 | Mansi | F | 19 | HISTORY | 1997-06-27 | 300 |
+--------+---------+----------+------+------------+--------------+------+
2 rows in set (0.00 sec)
20. Query Set 3: To write SQL- Queries for the following Questions based on the given table:
Rollno Name Gender Age Dept DOA Fees
1 Arun M 24 Computer 1997-01-10 120
2 Ankit M 21 History 1998-03-24 200
3 Annu F 20 Hindi 1996-12-12 300
4 Mahesh M 19 NULL 1999-07-01 400
5 Ashok M 18 Hindi 1997-09-05 250
6 Mansi F 19 History 1997-06-27 300
7 Priya F 18 Computer 2023-06-27 210
8 Riya F 17 NULL 2023-02-17 200

a) Write a Query to list of female students in hindi department.


mysql> select name from stu where Dept='HINDI' AND GENDER='F';
+---------+
| Name |
+--------+
| Annu |
+---------+
1 row in set (0.00 sec)

b) Write a query to list the name of students whose ages are between 18 to 20.

mysql> select name from stu where AGE BETWEEN 18 AND 20;
+-----------+
| Name |
+------------+
| Annu |
| Mahesh |
| Ashok |
| Mansi |
| Priya. |
+------------+
5 rows in set (0.03 sec)

c) Write a query to display the name of the students whose name is starting with ‘A’ .
mysql> select name from stu where name like'A%';

+--------+
| Name |
+--------+
| Arun |
| Ankit |
| Annu |
| Ashok|
+--------+
4 rows in set (0.10 sec)

d) Write a query to display the name of the students whose name have second alphabet ‘n’ in
their names.
mysql> select name from stu where name like'_n%';

+-------+
| name |
+-------+
| Ankit |
| Annu |
+-------+
2 rows in set (0.00 sec)
e) Write a Query to delete the details of Roll number is 8.
mysql> DELETE FROM STU WHERE ROLLNO=8;
Query OK, 1 row affected (1.72 sec)
Output (after deletion)
mysql> select *from stu;
+--------+----------+---------+------+---------------+------------+--------+
| Rollno | Name | Gender | Age | Dept | DOA | Fees |
+--------+---------+----------+------+---------------+------------+--------+
| 1 | Arun | M | 24 | COMPUTER | 1997-01-10 | 120 |
| 2 | Ankit | M | 21 | HISTORY | 1998-03-24 | 200 |
| 3 | Annu | F | 20 | HINDI | 1996-12-12 | 300 |
| 4 | Mahesh | M | 19 | NULL | 1999-07-01 | 400 |
| 5 | Ashok | M | 18 | HINDI | 1997-06-27 | 250 |
| 6 | Mansi | F | 19 | HISTORY | 1997-06-27 | 300 |
| 7 | Priya | F | 22 | COMPUTER | 2023-06-27| 210 |
+--------+--------+-----------+-----+-----------------+--------------+------+
7 rows in set (0.00 sec)
21. Query Set 4: To write SQL- Queries for the following Questions based on the given table:
Rollno Name Gender Age Dept DOA Fees
1 Arun M 24 Computer 1997-01-10 120
2 Ankit M 21 History 1998-03-24 200
3 Anu F 20 Hindi 1996-12-12 300
4 Bala M 19 NULL 1999-07-01 400
5 Charan M 18 Hindi 1997-09-05 250
6 Deepa F 19 History 1997-06-27 300
7 Dinesh M 22 Computer 1997-02-25 210
8 Usha F 23 NULL 1997-07-31 200

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

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


-> FEES<130;
Query OK, 1 row affected (2.69 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Output (after update)

+--------+---------+---------+------+----------------+--------------+--------+
| Rollno | Name | Gender | Age | Dept | DOA | Fees |
+--------+---------+---------+------+----------------+---------------+-------+
| 1 | Arun | M | 24 | COMPUTER | 1997-01-10 | 170 |
+--------+---------+---------+------+-----------------+--------------+-------+

b) Write a Query to add a new column Area of type varchar in table STU.
mysql> ALTER TABLE STU ADD AREA VARCHAR(20);
Query OK, 0 rows affected (2.12 sec)
Records: 0 Duplicates: 0 Warnings: 0

OUTPUT:
mysql> select*from stu;

+--------+---------+----------+------+---------------+-------------+------+---------+
| Rollno| Name | Gender | Age | Dept | DOA | Fees | AREA |
+--------+---------+---------+------+----------------+-------------+------+----------+
| 1 | Arun | M | 24 | COMPUTER | 1997-01-10 | 170 | NULL |
| 2 | Ankit | M | 21 | HISTORY | 1998-03-24 | 200 | NULL |
| 3 | Anu | F | 20 | HINDI | 1996-12-12 | 300 | NULL |
| 4 | Bala | M | 19 | NULL | 1999-07-01 | 400 | NULL |
| 5 | Charan | M | 18 | HINDI | 1997-06-27 | 250 | NULL |
| 6 | Deepa | F | 19 | HISTORY | 1997-06-27 | 300 | NULL |
| 7 | Dinesh | M | 22 | COMPUTER | 1997-02-25 | 210 | NULL |
+--------+---------+---------+------+----------------+--------------+------+--------+
7 rows in set (0.00 sec)

c) Write a Query to Display Name of all students whose Area Contains NULL.
mysql> SELECT NAME FROM STU WHERE AREA IS NULL;
+---------+
| NAME|
+---------+
| Arun |
| Ankit |
| Anu |
| Bala |
| Charan |
| Deepa |
| Dinesh |
+---------+
7 rows in set (0.08 sec)
d) Write a Query to delete Area Column from the table STU.
mysql> ALTER TABLE STU DROP AREA;
Query OK, 0 rows affected (2.46 sec)
Records: 0 Duplicates: 0 Warnings: 0

e) Write a Query to delete table from database.


mysql> drop table stu;
Query OK, 0 rows affected (7.32 sec)
22. Query set 5: To write SQL- Queries for the following Questions based on the given two table:
TABLE:STOCK
Pno Pname Dcode Qty UnitPrice StockDate
005 Ball pen 102 100 10 2024-03-31
003 Gel pen premium 102 150 15 2024-01-01
002 Pencil 101 125 4 2024-02-18
006 Scale 101 200 6 2023-01-01
001 Eraser 102 210 3 2023-03-19
004 Sharpner 102 60 5 2023-12-09
009 Gel pen classic 103 160 8 2022-01-19

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

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

mysql> select sum(UnitPrice) from stock GROUP BY Dcode HAVING Dcode=102;

+--------------------+
| sum(UnitPrice) |
+--------------------+
| 33.00 |
+--------------------+
1 row in set (0.25 sec)

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

mysql> SELECT * FROM STOCK ORDER BY STOCKDATE DESC;

+-----+---------------------+--------+------+------------+--------------+
| Pno | Pname | Dcode | Qty | UnitPrice | StockDate |
+-----+---------------------+--------+------+------------+--------------+
| 5 | Ball pen | 102 | 100 | 10.00 | 2024-03-31 |
| 2 | Pencil | 101 | 125 | 4.00 | 2024-02-18 |
| 3 | Gel pen premium | 102 | 150 | 15.00 | 2024-01-01 |
| 4 | Sharpner | 102 | 60 | 5.00 | 2023-12-09 |
| 1 | Eraser | 102 | 210 | 3.00 | 2023-03-19 |
| 6 | Scale | 101 | 200 | 6.00 | 2023-01-01 |
| 9 | Gel pen classic | 103 | 160 | 8.00 | 2022-01-19 |
+-----+---------------------+--------+------+-------------+--------------+
7 rows in set (0.00 sec)

c) To display maximum unit price of products for each dealer individually as per dcode from
the table Stock.
mysql> SELECT DCODE,MAX(UNITPRICE) FROM STOCK
-> GROUP BY DCODE;
+-----------+---------------------------+
| DCODE | MAX(UNITPRICE) |
+-----------+---------------------------+
| 102 | 15.00 |
| 101 | 6.00 |
| 103 | 8.00 |
+-----------+----------------------------+
3 rows in set (0.04 sec)

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

mysql> SELECT PNAME,DNAME FROM STOCK S,DEALERS D


-> WHERE S.DCODE=D.DCODE;
+----------------------+------------------------+
| PNAME | DNAME |
+----------------------+------------------------+
| Eraser | Classic Stationeries |
| Pencil | Sakthi Stationeries |
| Gel pen premium | Classic Stationeries |
| Sharpner | Classic Stationeries |
| Ball pen | Classic Stationeries |
| Scale | Sakthi Stationeries |
| Gel pen classic | Indian Book House |
+-----------------------+------------------------+
7 rows in set (0.10 sec)
23. Write a program in python using mysql python connectivity to create
table student, insert data into student table and display record.
CODE:
import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="1234")
cur=mycon.cursor()
cur.execute("create database if not exists school")
cur.execute("use school")
cur.execute("create table if not exists student(id int,name varchar(30),class int,subject
varchar(15))")
choice=0
while choice!=3:
print("1.Add new Record")
print("2.Display Record")
print("3.Exit")
choice=int(input("Enter Choice : "))
if choice==1:
i=int(input("Enter student ID: "))
n=input("Enter name of student: ")
c=int(input("Enter class in number: "))
s=input("Enter subject : ")
query="insert into student values({},'{}',{},'{}')".format(i,n,c,s)
cur.execute(query)
mycon.commit()
print("Record Added")
elif choice==2:
query="select * from student"
cur.execute(query)
result=cur.fetchall()
for row in result:
print(row)
elif choice==3:
mycon.close()
print("Exited")
else:
print("Invalid choice!!!")

OUTPUT:
24. Write a program using mysql python connectivity to search the record of a student
using ID from student table.
CODE:
import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="1234",database='school'
)
cur=mycon.cursor()
choice='y'
while choice=='y' or choice=='Y':
i=int(input("Enter student ID to be searched: "))
query="select * from student where id={}".format(i)
cur.execute(query)
result=cur.fetchall()
if cur.rowcount==0:
print("Student ID not found")
else:
for row in result:
print(row)

choice=input("Want to search more??? (y/n)")

OUTPUT:
25.Write a program using python mysql connectivity to update subject of a student.
import mysql.connector
mycon=mysql.connector.connect(host="localhost",username="root",passwd="123456",database=
'school')
cur=mycon.cursor()
choice='y'
while choice=='y' or choice=='Y':
cur.execute("Select * from student")
res=cur.fetchall()
for row in res:
print(row)
i=int(input("Enter student ID to update data : "))
j=input("Enter new subject :")
query="update student set subject='{}' where id={}".format(j,i)
cur.execute(query)
mycon.commit()
a=cur.rowcount
print(a,"rows updated")
cur.execute("select * from student")
result=cur.fetchall()
for row in result:
print(row)
choice=input("Want to update more??? (y/n)")

OUTPUT :
26. Write a program using python mysql connectivity to delete a record from student table.
import mysql.connector
mycon=mysql.connector.connect(host="localhost",username="root",passwd="123456",database=
'school')
cur=mycon.cursor()
choice='y'
while choice=='y' or choice=='Y':
cur.execute("Select * from student")
res=cur.fetchall()
for row in res:
print(row)
i=int(input("Enter student ID to delete : "))
query="delete from student where id={}".format(i)
cur.execute(query)
mycon.commit()
a=cur.rowcount
print(a,"rows deleted")
cur.execute("select * from student")
result=cur.fetchall()
for row in result:
print(row)

choice=input("Want to delete more??? (y/n)")


OUTPUT:

You might also like