0% found this document useful (0 votes)
22 views33 pages

Xii - CS Practical Programs (Final)

Uploaded by

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

Xii - CS Practical Programs (Final)

Uploaded by

gopin2127
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

GRADE : XII COMPUTER SCIENCE

PRACTICAL PROGRAMS (PYTHON AND SQL)

1) QUESTION:

Write a python program to take 5 subject marks as input and display the grade.

AIM:

To write a python program to take 5 subject marks as input and display the grade.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read 5 subject marks from user
STEP 3: Find average by adding the user’s marks and dividing by 5
STEP 4: Check the average score and assign grade
STEP 5: Print grade
STEP 6: Stop the program

PROGRAM:
sub1=int(input("Enter marks of the first subject: "))
sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
average=(sub1+sub2+sub3+sub4+sub5)/5
if(average>=90):
print("Grade: A")
elif(average>=80 and average <90):
print("Grade: B")
elif(average >=70 and average <80):
print("Grade: C")
elif(average >=60 and average <70):
print("Grade: D")
else:
print("Grade: F")
INPUT:
Enter marks of the first subject: 76
Enter marks of the second subject: 70
Enter marks of the third subject: 65
Enter marks of the fourth subject: 77
Enter marks of the fifth subject: 80
1
OUTPUT:

Grade:C

RESULT:

Thus , the program was executed successfully.

__________________________________________________________________________

2) QUESTION:

Write a python program to compute prime factors of an integer.

AIM:

To write a python program to compute prime factors of an integer.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read an integer n from user
STEP 3: Check if n is divisible by i
STEP 4: If divisible, check if i is prime
STEP 5: If i is prime, print i
STEP 6: Increment i, repeat step 3 to 6 until i<=n
STEP 7: Stop the program

PROGRAM:
#To compute prime factors of an integer
n=int(input("Enter an integer:"))
print("Factors are:")
i=1
while(i<=n):
k=0
if(n%i==0):
j=1
while(j<=i):
if(i%j==0):
k=k+1
j=j+1
if(k==2):
print(i)
i+=1

2
INPUT:
Enter an integer:6

OUTPUT:

Factors are:
2
3
RESULT:

Thus, the program was executed successfully.

__________________________________________________________________________

3) QUESTION:

Write a python program to transpose a matrix.

AIM:

To write a python program to transpose a matrix.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the input matrix
STEP 3: Initialize empty list for result
STEP 4: Loop through the first list and converts its rows into columns of the second list
using L1[i] [j] = L2[j] [i]
STEP 5: Display result
STEP 6: Stop the program
PROGRAM:
x=[[0,0,0],[0,0,0],[0,0,0]]
for i in range(3):
for j in range(3):
w=int(input("Enter a number:"))
x[i][j]=w
print("Given matrix is:\n")
for r in x:
print(" [", end=" ")
3
for i in r:
print(i,end=" ")
print("]")
print("\n")
result=[[0,0,0],[0,0,0],[0,0,0]]
print("Transpose matrix is: \n")
for i in range(3):
for j in range(3):
result[j][i]=x[i][j]
for r in result:
print(" [", end=" ")
for i in r:
print(i,end=" ")
print("]")
print("\n")
INPUT:
Enter a number:1
Enter a number:2
Enter a number:3
Enter a number:4
Enter a number:5
Enter a number:6
Enter a number:7
Enter a number:8
Enter a number:9

OUTPUT:
Given matrix is:
[123]
[456]
[789]
Transpose matrix is:
[147]
[258]
[369]
RESULT:
Thus, the program was executed successfully.
4
4) QUESTION:

Write a python program to count and display the vowels of a given text.

AIM:

To write a python program to count and display the vowels of a given text.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read string from user
STEP 3: Initialise a list with vowels and count to 0
STEP 4: Traverse through the string using loop
STEP 5: Check if the character is in vowel list
STEP 6: If so, add 1 to count, repeat step 4 to 6 until the end of string
STEP 7: Display count
STEP 8: Stop the program

PROGRAM:
text = input(“Enter a String:”)
vowels = ‘aeiouAEIOU’
vowelcount = 0
for i in text:
if i in vowels:
vowelcount += 1
print(“Number of vowels in the given string is:” , vowelcount)
INPUT:

Enter a String: I am a computer science student

OUTPUT:

Number of vowels in the given string is: 11

RESULT:

Thus, the program was executed successfully.

__________________________________________________________________________

5
5) QUESTION:

Write a python program to check the number is prime or not by using function.

AIM:

To write a python program to check the number is prime or not by using function.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the number n
STEP 3: Call the function to check if the number is prime.
STEP 4: If n is one set result as False, Go to step 7
STEP 5: If n is two set result as True, Go to step 7
STEP 6: Check if ‘n’ is divisible by any number between 2 and n-1, if divisible set result as
true else false
STEP 7: If result is True display that “number is prime”
STEP 8: Stop the program.

PROGRAM:
def isprime(n):
if(n==1):
return False
elif(n==2):
return True
else:
for x in range(2,n):
if(n%x==0):
return False
else:
return True
num=int(input("Enter a number:"))
s=isprime(num)
if(s):
print(num,"is a prime number")
else:
print(num,"is not a prime number")
INPUT:
Enter a number:14
OUTPUT:
14 is not a prime number
6
RESULT:
Thus, the program was executed successfully.

__________________________________________________________________________

6) QUESTION:

Write a python program to check whether the passed string is palindrome or not by
using user defined function.

AIM:

To write a python program to check whether the passed string is palindrome or not by
using user defined function.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the string s
STEP 3: Call the function
STEP 4: Initialise left pos to 0 and right pos to length of string-1, result true.
STEP 5: Repeat step 6 and 7 until left pos is less than right pos
STEP 6: Check if characters in left pos of s is equal characters in right pos
STEP 7: If yes, add1 to left pos and subtract 1 from right pos, if not then set result as false
STEP 8: If result is true then display, “String is Palindrome” else display “String is not
Palindrome”
STEP 9: Stop the program

PROGRAM:
def ispalindrome(str):
leftpos=0
rightpos=len(str)-1
while(rightpos >= leftpos):
if(not(str[leftpos]== str[rightpos])):
return False
leftpos+=1
rightpos-=1
return True
str=input("Enter a string:")
if(ispalindrome(str)):
print("The Given String is Palindrome")
else:
print("The Given String is Not a Palindrome")
7
INPUT:
Enter a string:madam

OUTPUT:

The Given String is Palindrome

RESULT:
Thus, the program was executed successfully.

__________________________________________________________________________

7) QUESTION:

Write a python program to find area of the given shape using math module.

AIM:

To write a python program to find area of the given shape using math module.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the name of the shape from user
STEP 3: If it is a circle, read radius and find area using formula pi*r2 and go to step 6
STEP 4: If it is a square, read side and find area using formula side**2 and go to step 6
STEP 5: If it is a rectangle, read l, b and find area using formula l*b and go to step 6
STEP 6: If any other shape, display “Shape not Defined” and end
STEP 7: Display area
STEP 8: Stop the program.
PROGRAM:

import math
def calculate_area(name):
# converting all characters into lower cases
name = name.lower()
if name.lower()=="rectangle":
l = int(input("Enter rectangle's length:"))
b = int(input("Enter rectangle's breadth:"))
rect_area = l * b
print("The area of rectangle is:",rect_area)

8
elif name.lower() == "square":
s = int(input("Enter square's side length:"))
sqt_area = math.pow(s,2)
print("The area of square is:",sqt_area)
elif name.lower() == "triangle":
h = int(input("Enter triangle's height length:"))
b = int(input("Enter triangle's breadth length:"))
tri_area = 0.5 * b * h
print("The area of triangle is:",tri_area)
elif name.lower() == "circle":
r = int(input("Enter circle's radius length:"))
circ_area=math.pi*pow(r,2)
print("The area of circle is:",circ_area)
elif name.lower() == 'parallelogram':
b = int(input("Enter parallelogram's base length:"))
h = int(input("Enter parallelogram's height length:"))
para_area = b * h
print("The area of parallelogram is:",para_area)
else:
print("Sorry! This shape is not available")
shape_name = input("Enter the name of shape
rectangle/square/triangle/circle/parallelogram:")
calculate_area(shape_name)
INPUT:
Enter the name of shape rectangle/square/triangle/circle/parallelogram:square
Enter square's side length:4
OUTPUT:

The area of square is: 16.0

RESULT:
Thus, the program was executed successfully.

__________________________________________________________________________
9
8) QUESTION:

Write a python program to find the factorial of the given number.

AIM:

To write a python program to find the factorial of the given number.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read number ‘n’
STEP 3: If number is 1 or 2 display n. End
STEP 4: Initialise i to 1, factorial to 1
STEP 5: Calculate factorial = factorial * i
STEP 6: Increase value of i by 1 and repeat step 5 until i is equal to n
STEP 7: Display factorial
STEP 8: Stop the program

PROGRAM:

num = int(input("Enter a number:"))


factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

INPUT:
Enter a number:5

OUTPUT:
The factorial of 5 is 120

RESULT:
Thus, the program was executed successfully.

__________________________________________________________________________

10
9) QUESTION:

Write a python program to remove punctuation from given string.

AIM:

To write a python program to remove punctuation from given string.

ALGORITHM:

STEP 1: Start the program


STEP 2: Initialise string punctuation
STEP 3: Read string s
STEP 4: Initialise an empty string s1
STEP 5: Traverse through string using loop
STEP 6: If character is not in punctuation copy to s1
STEP 7: Repeat step 6 till end of string
STEP 8: Display s1
STEP 9: Stop the program

PROGRAM:

punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
my_str = input("Enter the string with punctuations:")
no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char
print(no_punct)

INPUT:
Enter the string with punctuations:"computer*#science"

OUTPUT:
computerscience
RESULT:
Thus, the program was executed successfully.

_________________________________________________________________________

11
10) QUESTION:

Write a python program to append text to a text file and read line by line.

AIM:

To write a python program to append text to a text file and read line by line.

ALGORITHM:

STEP 1: Start the program


STEP 2: open the text file in append mode
STEP 3: Read text content from user
STEP 4: Write the text in file
STEP 5: Close the file
STEP 6: Open the file in read mode
STEP 7: Read the file line by line and display
STEP 8: Close the file
STEP 9: Stop the program.

PROGRAM:

f = open ("d:\\a.txt", "a")


s = input ("Enter a string to add at end of file:")
f.write (s)
f.close ( )
f = open ("d:\\a.txt", "r")
for t in f.readlines( ):
print(t , end = " ")
f.close( )

INPUT:
Enter a string to add at end of file: Python

OUTPUT:
Computer Science Computer Science Computer Science Python

RESULT:
Thus, the program was executed successfully.

__________________________________________________________________________

12
11) QUESTION:

Write a python program to count number of words starting with capital letter and
number of words starting with small letter in a text file.

AIM:

To write a python program to count number of words starting with capital letter and
number of words starting with small letter in a text file.

ALGORITHM:

STEP 1: Start the program


STEP 2: Open the file in read mode, initialise c and s is 0
STEP 3: Read each line of the text file
STEP 4: Split words in the line
STEP 5: If first letter of word is capital, increment c else increment s
STEP 6: Display c, s
STEP 7: Close the file
STEP 8: Stop the program
PROGRAM:
f=open("d:\\a.txt","r")
c=0
s=0
for t in f.readlines( ):
for r in t.split( ):
if(r[0].isupper( )):
c+=1
elif(r[0].islower( )):
s+=1
else:
pass
print("No. of words starting with capital letter",c)
print("No. of words starting with small letter",s)
f.close( )

OUTPUT:
No. of words starting with capital letter 8
No. of words starting with small letter 2

RESULT:
Thus, the program was executed successfully.
13
12) QUESTION:

Write a python program to store students details in text file and read the same.

AIM:

To write a python program to store students details in text file and read the same.

ALGORITHM:

STEP 1: Start the program


STEP 2: Open text file in append mode
STEP 3: Read number of students in class
STEP 4: Read students roll no, name, and mark
STEP 5: Write to the file
STEP 6: Close the file
STEP 7: Open file in read mode
STEP 8: Read lines from file and display using loop
STEP 9: Close the file
STEP 10: Stop the program
PROGRAM:
count=int(input("How many students are there in class?:"))
fileout=open("marks.txt", "w")
for i in range(count):
print("Enter details of students:",(i+1))
rollno=int(input("Roll number:"))
name=input("Name:")
mark=float(input("Marks:"))
rec=str(rollno) + "," + name + "," + str(mark) + "\n"
fileout.write(rec)
fileout.close()
fileinp=open("marks.dat","r")
while str:
str=fileinp.readline()
print(str)
fileinp.close()
INPUT:
How many students are there in class?:3
Enter details of students: 1
Roll number:250201
Name:Pooja
Marks:97
14
Enter details of students: 2
Roll number:250202
Name:Arya
Marks:85
Enter details of students: 3
Roll number:250203
Name:Raja
Marks:69
OUTPUT:
250201, Pooja, 97
250202, Arya, 85
250203, Raja, 69

RESULT:
Thus, the program was executed successfully.

__________________________________________________________________________

13) QUESTION:

Write a python program to read and store details of 5 students in csv file.

AIM:

To write a python program to read and store details of 5 students in csv file.

ALGORITHM:

STEP 1: Start the program


STEP 2: Open csv file in append mode
STEP 3: Create object for writing
STEP 4: Read students rollno, name, mark and convert it
STEP 5: Write the list to the csv file
STEP 6: Close the file
STEP 7: Open file in read mode
STEP 8: Close the file
STEP 9: Stop the program
PROGRAM:
import csv
with open("student.csv", "w") as fh:
stuwriter = csv.writer(fh)
stuwriter.writerow(['Rollno', 'Name', 'Marks'])
for i in range(5):
15
print("Student record", (i+1))
Rollno = int(input("Enter Rollno:"))
Name = input("Enter Name:")
Marks =float( input("Enter Marks:"))
sturec = [Rollno, Name, Marks]
stuwriter.writerow(sturec)
with open("student.csv", 'r') as fh:
creader = csv.reader(fh)
for rec in creader:
print(rec)

INPUT:
Student record 1
Enter Rollno:101
Enter Name:Alice
Enter Marks:93

Student record 2
Enter Rollno:102
Enter Name:Arjun
Enter Marks:77

Student record 3
Enter Rollno:103
Enter Name:Senthil
Enter Marks:86

Student record 4
Enter Rollno:104
Enter Name:Madhumitha
Enter Marks:69

Student record 5
Enter Rollno:105
Enter Name:Sumitha
Enter Marks:99

16
OUTPUT:

['Rollno', 'Name', 'Marks']


[ ]
['101', 'Alice', '93']
[ ]
['102', 'Arjun', '77']
[ ]
['103', 'Senthil', '86']
[ ]
['104', 'Madhumitha', '69']
[ ]
['105', 'Sumitha', '99']
[ ]
RESULT:
Thus, the program was executed successfully.

__________________________________________________________________________

14) QUESTION:

Write a python program to store and read the details of students in binary file.

AIM:

To write a python program to store and read the details of students in binary file.

ALGORITHM:

STEP 1: Start the program


STEP 2: Open binary file in append mode
STEP 3: Create an empty list
STEP 4: Read students rollno, name, subject, mark and convert into list
STEP 5: Write to the file
STEP 6: Get user option if they want to enter another students details
STEP 7: If yes, repeat step 4 to 6 else go to step 8
STEP 8: Close the file
STEP 9: Open file in read mode
STEP10: Read lines from file and display using loops
STEP 11: Close the file
STEP 12: Stop the program

17
PROGRAM:

import pickle
stu=[ ]
stufile = open('stu.dat', 'ab')
ans = 'y'
while ans == 'y':
mark = [ ]
rno = int(input("Enter the roll number: "))
name = input("Enter name: ")
for i in range(3):
a = float(input("Enter the marks:”,(i+1)))
mark.append(a)
stu = [rno, name, mark]
pickle.dump(stu, stufile)
ans = input("Want to append more records? (Y/N): ").lower()
stufile.close()
stu = [ ]
stufile = open('stu.dat', 'rb')
try:
while True:
stu = pickle.load(stufile)
print(stu)
except EOFError:
stufile.close( )
INPUT:
Enter the roll number: 101
Enter name: Suresh
Enter the mark 1: 90
Enter the mark 2: 81
Enter the mark 3: 75
Want to append more records? (Y/N): Y
Enter the roll number: 102
Enter name: Vignesh
Enter the mark 1: 65
Enter the mark 2: 54
Enter the mark 3: 69
Want to append more records? (Y/N): N

18
OUTPUT:
[101, 'Suresh', [90, 81, 75]]
[102, 'Vignesh', [65, 54, 69]]

RESULT:
Thus, the program was executed successfully.

__________________________________________________________________________

15) QUESTION:

Write a python program to read students detail from binary file and display records of
students whose mark is greater than 81.

AIM:

To write a python program to read students detail from binary file and display records
of students whose mark is greater than 81.

ALGORITHM:

STEP 1: Start the program


STEP 2: Open binary file in read mode
STEP 3: Read one student detail from file
STEP 4: Check if mark is greater than 81.If yes then display student details, if no go to step
3.Repeat steps 3, 4 until end of file.
STEP 5: Close the file
STEP 6: Stop the program

PROGRAM:

import pickle
found = False
print("Searching in file stu.dat")
with open("stu.dat", "rb") as fin:
students = pickle.load(fin)
for student in students:
if student['mark'] > 81:
print(student)
found = True
if not found:
print("No records with marks greater than 81")

19
OUTPUT:
[101, 'Suresh', [90, 81, 75]]
RESULT:
Thus, the program was executed successfully.

__________________________________________________________________________

16) QUESTION:

Write a python program to reverse a string using stack.

AIM:

To write a python program to reverse a string using stack.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the string
STEP 3: Traverse through the string using loop and push characters using the stack
STEP 4: Pop the characters of the stack and add it to the empty string s1 using loop
STEP 5: Display s1
STEP 6: Stop the program

PROGRAM:
def isEmpty(stack):
return len(stack) == 0
def push(stack, item):
stack.append(item)
def pop(stack):
if isEmpty(stack):
return "underflow"
else:
return stack.pop()
def reverse(string):
n = len(string)
stack = []
for i in range(0, n, 1):
push(stack, string[i])
20
reversed_string = ""
for i in range(0, n, 1):
reversed_string += pop(stack)
return reversed_string
string = input("Enter the string to be reversed: ")
result = reverse(string)
print("Reversed string is: " + result)
INPUT:
Enter the string to be reversed: Computer
OUTPUT:
Reversed string is: retupmoC
RESULT:
Thus, the program was executed successfully.

_________________________________________________________________________

17) QUESTION:

Write a python program to add a new column to the table employee

AIM:

To write a python program to add a new column to the table employee.

ALGORITHM:

STEP 1: Start the program


STEP 2: Import the needed modules
STEP 3: Connect the database
STEP 4: Create a cursor variable to use the database
STEP 5: Create a table employee with attributes empid, name, salary and address
STEP 6: Alter table employee to add a new attribute designation
STEP 7: Display the structure of the table
STEP 8: Close the connection
STEP 9: Stop the program
PROGRAM:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
21
database="empl"
)
mycursor = mydb.cursor()
mycursor.execute("""
CREATE TABLE employee (
id INT(5),
name VARCHAR(20),
salary INT(5),
address VARCHAR(30)
)
""")
mycursor.execute("ALTER TABLE employee ADD COLUMN designation
VARCHAR(30)")
mycursor.execute("DESCRIBE employee")
for x in mycursor.fetchall():
print(x)
mycursor.close()
mydb.close()

OUTPUT:
Field Datatype Size Constraint
id integer 11 PRIMARY KEY
name varchar 20
salary integer 11
address varchar 30
designation varchar 30

RESULT:
Thus, the program to add a new column was executed successfully.

_________________________________________________________________________

18) QUESTION:

Write a python program to create employee table with attributes ID, name, address,
salary and insert data in it using SQL queries.

AIM:

To write a python program to create employee table with attributes ID, name, address,
salary and insert data in it using SQL queries.

22
ALGORITHM:

STEP 1: Start the program


STEP 2: Import the needed modules
STEP 3: Connect the database
STEP 4: Create a cursor variable to use the database
STEP 5: Create table with the required file by using CREATE TABLE command
STEP 6: Display “values added into the table”
STEP 7: Close the connection
STEP 8: Stop the program
PROGRAM:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="empl"
)
mycursor = mydb.cursor()
mycursor.execute("""
CREATE TABLE empl (
id INT(2),
name VARCHAR(25),
salary INT(20),
address VARCHAR(30)
)
""")
mycursor.execute("SHOW TABLES")
for table in mycursor:
print(table)
mycursor.execute("INSERT INTO empl VALUES (2, 'ashwin', 3000, 'mumbai')")
mycursor.execute("INSERT INTO empl VALUES (3, 'amith', 10000, 'mumbai')")
print(mycursor.rowcount, "was inserted")
mycursor.execute("SELECT * FROM empl")
for row in mycursor:
print(row)
mydb.commit()
mycursor.close()
mydb.close()

23
OUTPUT:
2 was inserted
(2, 'ashwin', 3000, 'mumbai')
(3, 'amith', 10000, 'mumbai')
RESULT:
Thus, the program was executed successfully.

_________________________________________________________________________

19) QUESTION:

Write a python program to read the details of employees whose salary is greater than
5000 using sql queries.

AIM:

To write a python program to read the details of employees whose salary is greater
than 5000 using sql queries.

ALGORITHM:

STEP 1: Start the program


STEP 2: Import the needed modules
STEP 3: Connect the database
STEP 4: Create a cursor variable to use the database
STEP 5: Read the details of employees whose salary is greater than 5000 using SELECT
command.
STEP 6: Display the record using loop
STEP 7: Stop the program
PROGRAM:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="empl"
)
mycursor = mydb.cursor()
mycursor.execute("""
CREATE TABLE empl (
id INT(2),
name VARCHAR(25),
salary INT(20),
24
address VARCHAR(30)
)
""")
mycursor.execute("SHOW TABLES")
for table in mycursor:
print(table)
mycursor.execute("INSERT INTO empl VALUES (1, 'amith', 10000, 'mumbai')")
print(mycursor.rowcount, "was inserted")
mycursor.execute("SELECT * FROM empl WHERE salary > 5000")
for row in mycursor:
print(row)
mydb.commit()
mycursor.close()
mydb.close()

OUTPUT:
1 was inserted
(1, 'amith', 10000, 'mumbai')
RESULT:
Thus, the program was executed successfully.

_________________________________________________________________________

20) QUESTION:

Write a python program to update salary by 2000 of employee who is in Mumbai


using sql queries.

AIM:

To write a python program to update salary by 2000 of employee who is in Mumbai


using sql queries.

ALGORITHM:

STEP 1: Start the program


STEP 2: Import the needed modules
STEP 3: Connect the database
STEP 4: Create a cursor variable to use the database
STEP 5: Update the salary of employees in mumbai
STEP 6: Display the record using loop
STEP 7: Stop the program
PROGRAM:
25
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="empl"
)
mycursor = mydb.cursor()
mycursor.execute("""
CREATE TABLE empl (
id INT(2),
name VARCHAR(25),
salary INT(20),
address VARCHAR(30)
)
""")
mycursor.execute("SHOW TABLES")
for table in mycursor:
print(table)
mycursor.execute("INSERT INTO empl VALUES (2, 'ashwin', 3000, 'mumbai')")
mycursor.execute("INSERT INTO empl VALUES (3, 'amith', 10000, 'mumbai')")
print(mycursor.rowcount, "was inserted")
mycursor.execute("UPDATE empl SET salary=salary + 2000 WHERE address= 'mumbai'")
mycursor.execute("SELECT * FROM empl")
for row in mycursor:
print(row)
mydb.commit()
mycursor.close()
mydb.close()

OUTPUT:
2 was inserted
(2, 'ashwin', 5000, 'mumbai')
(3, 'amith', 12000, 'mumbai')
RESULT:
Thus, the program was executed successfully.

_________________________________________________________________________

26
21) QUESTION:

Write SQL query to create table ‘EMPLOYEE’ with attributes Empid, Firstname,
Lastname, Address, City with appropriate datatype and to insert 2 records into the table.

AIM:

To write SQL query to create table ‘EMPLOYEE’ with attributes Empid, Firstname,
Lastname, Address, City with appropriate datatype and to insert 2 records into the table.

SQL QUERY:

To Create table:

CREATE TABLE EMPLOYEE (

empid INT(3),

firstname VARCHAR(20),

lastname VARCHAR(20),

address VARCHAR(20),

city CHAR(20)

);

To Insert values:

INSERT INTO EMPLOYEE VALUES (001, 'Harish', 'Kalyan', 'Rajnagar', 'Mumbai');

INSERT INTO EMPLOYEE VALUES (002, 'Rishi', 'Kumar', 'Annanagar', 'Chennai');

OUTPUT:

Empid First name Last name Address City


001 Harish Kalyan Rajnagar Mumbai
002 Rishi Kumar Annanagar Chennai

RESULT:

Thus, the query was executed successfully.

__________________________________________________________________________

27
22) QUESTION:

Write Query to

(i) Create table empsalary as given below

Empid Empname Salary Designation


001 Rajesh 10,000 Asst. Manager
002 Suresh 15,000 Manager
003 Harish 7,000 Typist
004 Aathi 20,000 Manager
005 Rohan 9,000 Typist

(ii) insert record in table empsalary

(iii) List the name of the employees who got salary less than 10,000

AIM:

To write Query to Create table empsalary , insert record in table empsalary and List
the name of the employees who get less than 10,000.

SQL QUERY:

(i) To create table empsalary:

CREATE TABLE empsalary (

empid INT(10),

empname VARCHAR(30),

salary INT(20),

designation VARCHAR(15)

);

(ii) To insert record:

INSERT INTO empsalary VALUES (001, 'Rajesh', 10000, 'Asst.Manager');

INSERT INTO empsalary VALUES (002, 'Suresh', 15000, 'Manager');

INSERT INTO empsalary VALUES (003, 'Harish', 7000, 'Typist');

(iii) List name of employees who get salary less than 10,000:

SELECT empname FROM empsalary WHERE salary < 10000;


28
OUTPUT:

(iii)

Empname
Harish
Rohan

RESULT:

Thus,Query was executed successfully.

__________________________________________________________________________

23) QUESTION:

Write SQL query to add foreign key constraint to the table empsalary and display the
details and salary of employee who belongs to “Chennai”.

AIM:

To write SQL query to add foreign key constraint to the table empsalary and display
the details and salary of employee who belongs to “Chennai”.

SQL QUERY:

To Create table:

CREATE TABLE EMPLOYEE (

empid INT(3),

empname VARCHAR(20),

address VARCHAR(20),

city CHAR(20)

);

INSERT INTO empsalary (Empid, Empname, Salary, Designation) VALUES

(001, 'Rajesh', ‘Gandhi nagar’, 'Delhi'),

(002, 'Suresh', ‘Anna nagar’, 'Chennai'),

(003, ‘Harish’, 'A M nagar’ , 'Mumbai'),

29
(004, 'Aathi', ‘K K nagar’, 'Chennai'),

(005, 'Rohan', ‘Park street’, 'Kolkata');

To create empsalary:

CREATE TABLE empsalary (

empid INT(10),

salary INT(10),

designation VARCHAR(15),

FOREIGN KEY (empid) REFERENCES EMPLOYEE(empid)

);

INSERT INTO empsalary (Empid, Empname, Salary, Designation) VALUES

(001, 10000, 'Asst. Manager'),

(002, 15000, 'Manager'),

(003, 7000, 'Typist'),

(004, 20000, 'Manager'),

(005, '9000

, 'Typist');

To retrieve salary and name of the employee who is from Chennai:

SELECT empname,salary

FROM EMPLOYEE, empsalary

WHERE EMPLOYEE.empid = empsalary.empid;

OUTPUT:

(i) Employee table

Empid Empname Address City


001 Rajesh Gandhi nagar Delhi
002 Suresh Anna nagar Chennai
003 Harish A M nagar Mumbai
004 Aathi K K nagar Chennai
005 Rohan Park street Kolkata

30
(ii) Empsalary

Empid Salary Designation


001 10000 Asst Manager
002 15000 Manager
003 7000 Typist
004 20000 Manager
005 9000 Typist

(iii) Name and salary of the employee who is from Chennai:

Empname Empsalary
Suresh 15000
Aathi 20000
RESULT:

Thus, query was executed successfully.

_________________________________________________________________________

24) QUESTION:

CLUB

Coachid Coach name Age Sports D.O.B Pay Gender

1 Mega 35 Karate 27/3/1996 1000 F


2 Sunaina 34 Karate 20/1/1998 1200 F
3 Gana 34 Squash 19/1/1998 2000 F
4 Vivan 33 Basketball 01/1/1998 1500 M
5 Krishna 36 Karate 12/1/1998 750 M
6 Kumar 36 Swimming 24/2/1998 800 M
7 Prem 39 Squash 20/2/1998 2200 M
8 Praveena 37 Basketball 22/2/1998 1100 F
9 Nihal 41 Swimming 13/1/1998 900 F
Find out the output of the following queries based on the table CLUB.

(i) SELECT count(distinct age) FROM CLUB;

(ii) SELECT MIN(Pay) FROM club WHERE Gender = ‘M’;

(iii) SELECT SUM(Pay) FROM CLUB WHERE DOB > ‘31/1/1998’;

(iv)SELECT Sports, Count(Coachname) FROM CLUB Group by sports.


31
OUTPUT:

(i)

Count(distinct age)
7
(ii)

Min(pay)
750

(iii)

Sum(pay)
4100

(iv)

Sports Count(Coachname)
Karate 3
Squash 2
Basket ball 2
Swimming 2

RESULT:

Thus, query was executed successfully.

__________________________________________________________________________

25) QUESTION:

Find out output based on the SQL query based on student detail table.

STUDENT DETAIL TABLE

Rollno Name Class Mark


1201 Ramu 12 350
1103 Manohar 11 400
1204 Saroja 12 430
1102 Loganathan 11 320
1105 Rajalakshmi 11 450
1206 Marthandam 12 470

32
(i) Select * from student order by name;
(ii) Select count(*) class from student Group by class
(iii) Select max(Mark) from Student
OUTPUT:
(i)

Rollno Name Class Mark


1102 Loganathan 11 320
1103 Manohar 11 400
1206 Marthandam 12 470
1201 Ramu 12 350
1105 Rajalakshmi 11 450
1204 Saroja 12 430

(ii)

Count Class
3 12
3 11

(iii)

MAX(mark)
470

RESULT:

Thus, query was executed successfully.

_________________________________________________________________________

33

You might also like