0% found this document useful (0 votes)
10 views65 pages

Record File

python mysql and connectivity

Uploaded by

roniashanty
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)
10 views65 pages

Record File

python mysql and connectivity

Uploaded by

roniashanty
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/ 65

COMPUTER

SCIENCE
RECORD FILE ASSIGNMENTS
2024-2025

Name: Ivana Floraine Shanty


Grade: XII B
Roll No: 13
…………...
PROGRAM 1

Write a menu driven program using function to

• Find factorial of a number.


• Print first ‘n’ Prime numbers.
• To check if a number is a Palindrome or not.

Source Code:
def factorial(n):

if n==0:
return 1
else:
return n*factorial(n-1)
def prime():
L=[2, 3, 5, 7, 11]
for i in range(2,n+1000):
if i%6==0:
if (i-1)%5!=0:
if (i-1)%7!=0:
if (i-1)%11!=0:
L.append(i-1)
if (i+1)%5!=0:

if (i-1)%5!=0:
if (i+1)%7!=0:
if (i+1)%11!=0:
L.append(i+1)
for j in range(0,n):
print(L[j])
def palindrome(n):
x=n
y=0
while n>0:
z=n%10
y=y*10+z

n=n//10
if x==y:
print("The number is a palindrome.")
else:
print("The number is not a palindrome.")
while True:
print("1. Find factorial of a number.")
print("2. Print the first 'n' prime numbers.")
print("3. Check if a number is a palindrome.")
print()
ch=int(input("Enter your choice: "))
print()
if ch==1:

num=int(input("Enter a number to find its factorial: "))


print("Factorial:", factorial(num))
break
elif ch==2:
n=int(input("Enter the number of prime numbers to be printed: "))
prime()
break
elif ch==3:
num=int(input("Enter a number to check if it is a palindrome: "))
palindrome(num)
break
elif ch==0:

print("Exiting program.")
break
else:
print("Invalid choice.")

Output:
1. Find factorial of a number.
2. Print the first 'n' prime numbers.
3. Check if a number is a palindrome.

Enter your choice: 1


Enter a number to find its factorial: 7
Factorial: 5040

1. Find factorial of a number.


2. Print the first 'n' prime numbers.
3. Check if a number is a palindrome.
Enter your choice: 2

Enter the number of prime numbers to be printed: 8


2
3
5
7
11
13
17
19

1. Find factorial of a number.


2. Print the first 'n' prime numbers.
3. Check if a number is a palindrome.
Enter your choice: 3

Enter a number to check if it's a palindrome: 18 The


number is not a palindrome.

1. Find factorial of a number.


2. Print the first 'n' prime numbers.
3. Check if a number is a palindrome.
Enter your choice: 3
Enter a number to check if it's a palindrome: 18 The
number is not a palindrome.

1. Find factorial of a number.


2. Print the first 'n' prime numbers.
3. Check if a number is a palindrome.
Enter your choice: 4
Invalid choice.

1. Find factorial of a number.


2. Print the first 'n' prime numbers.
3. Check if a number is a palindrome.
Enter your choice: 0
Exiting program.

PROGRAM 2

Write a menu driven program using function to


• Check if a given string is a Palindrome.
• Count the number of alphabets, special characters, digits in a string.
• Remove all vowels from a string.

Source Code:
def palindrome():
str1 = input("Enter the string: ")
l = len(str1)
p=l-1
index = 0
while index < p:
if str1[index] == str1[p]:
index += 1
p -= 1
else:
print("The string is not a palindrome.")
return
print("The string is a palindrome.")

def count(string):
a=0
d=0
sc = 0
for char in string:
if char.isalpha():
a += 1
elif char.isdigit():
d += 1
else:
sc += 1
print("The number of alphabets is", a)
print("The number of digits is", d)
print("The number of special characters is", sc)

def remove():
str1 = input("Enter the string: ")
s = ""
for i in range(len(str1)):
if str1[i] not in "aeiouAEIOU":
s = s + str1[i]
print("Original string is:", str1)
print("New string is:", s)

while True:
print("1. Check if a given string is a Palindrome.")
print("2. Count the number of alphabets, special characters, digits in a
string.")
print("3. Remove all vowels from a string.")
ch = int(input("Enter your choice: "))
if ch == 1:
palindrome()
break
elif ch == 2:
str1 = input("Enter the string: ")
count(str1)
break
elif ch == 3:
remove()
break
elif ch==0:
print("Exiting program.")
break
else:
print("Invalid choice.")
Output:
1. Check if a given string is a Palindrome.
2. Count the number of alphabets, special characters, digits in a string.
3. Remove all vowels from a string.

Enter your choice: 1


Enter the string: madam
The string is a palindrome.

1. Check if a given string is a Palindrome.


2. Count the number of alphabets, special characters, digits in a string.
3. Remove all vowels from a string.
Enter your choice: 1
Enter the string: pencil
The string is not a palindrome.

1. Check if a given string is a Palindrome.

2. Count the number of alphabets, special characters, digits in a string.


3. Remove all vowels from a string.
Enter your choice: 2
Enter the string: welcome t0 thi$ prog4m.
The number of alphabets is: 16
The number of digits is: 2
The number of special characters is: 5

1. Check if a given string is a Palindrome.


2. Count the number of alphabets, special characters, digits in a string.
3. Remove all vowels from a string.
Enter your choice: 3
Enter the string: python program
Original string is: python program
New string is: pythn prgrm

1. Check if a given string is a Palindrome.

2. Count the number of alphabets, special characters, digits in a string.


3. Remove all vowels from a string.
Enter your choice: 4
Invalid choice.

1. Check if a given string is a Palindrome.


2. Count the number of alphabets, special characters, digits in a string.
3. Remove all vowels from a string.
Enter your choice: 0
Exiting program.

PROGRAM 3
Write a menu driven program to

• Find the sum of all elements of a list.


• Find the largest element in a list
• Calculates sum of even numbers in the list.
• Calculates sum of odd numbers in the list.

Source Code:

def total_sum(lst):
return sum(lst)
def largest(lst):
return max(lst)
def even(lst):
return sum(n for n in lst if n % 2 == 0)
def odd(lst):
return sum(n for n in lst if n % 2 != 0)
print("1. Find the sum of all elements of a list.")
print("2. Find the largest element in a list.")
print("3. Calculate sum of even numbers in the list.")
print("4. Calculate sum of odd numbers in the list.")
ch = int(input("Enter your choice: "))
if ch == 1:
lst = [int(n) for n in input("Enter the list of numbers separated by a space:
").split()]
print("Sum of all elements:", total_sum(lst))
break
elif ch == 2:
lst = [int(n) for n in input("Enter the list of numbers separated by a space:
").split()]
print("Largest element:", largest(lst))
break
elif ch == 3:
lst = [int(n) for n in input("Enter the list of numbers separated by a space:
").split()]
print("Sum of even numbers:", even(lst))
break
elif ch == 4:
lst = [int(n) for n in input("Enter the list of numbers separated by a space:
").split()]
print("Sum of odd numbers:", odd(lst))
break
elif ch == 0:
print(“Exiting program.”)
else:
print("Invalid choice.")

Output:
1. Find the sum of all elements of a list.
2. Find the largest element in a list.
3. Calculate sum of even numbers in the list.
4. Calculate sum of odd numbers in the list.
Enter your choice: 1
Enter the list of numbers separated by a space: 2 5 7 9
Sum of all elements: 23

1. Find the sum of all elements of a list.


2. Find the largest element in a list.
3. Calculate sum of even numbers in the list.
4. Calculate sum of odd numbers in the list.
Enter your choice: 2
Enter the list of numbers separated by a space: 2 5 6 3 8
Largest element: 8

1. Find the sum of all elements of a list.


2. Find the largest element in a list.
3. Calculate sum of even numbers in the list.
4. Calculate sum of odd numbers in the list.
Enter your choice: 3
Enter the list of numbers separated by a space: 1 2 3 4
Sum of even numbers: 6

1. Find the sum of all elements of a list.


2. Find the largest element in a list.

3. Calculate sum of even numbers in the list.


4. Calculate sum of odd numbers in the list.
Enter your choice: 4
Enter the list of numbers separated by a space: 1 2 3 4
Sum of odd numbers: 4

1. Find the sum of all elements of a list.


2. Find the largest element in a list.
3. Calculate sum of even numbers in the list.
4. Calculate sum of odd numbers in the list.

Enter your choice: 5


Invalid choice.
1. Find the sum of all elements of a list.

2. Find the largest element in a list.


3. Calculate sum of even numbers in the list.
4. Calculate sum of odd numbers in the list.
Enter your choice: 0
Exiting program.

PROGRAM 4

Write a random number generator that generates random numbers between 1


and 6 (simulates a dice).

Source Code:

import random

def dice():
return random.randint(1, 6)

print("The number is:", dice())

Output:
The number is: 1

PROGRAM 5

Write a menu driven program that accepts a List and calculates the

• Mean
• Median
• Mode

Source Code:

import statistics
def mean(n):
return statistics.mean(n)
def median(n):
return statistics.median(n)
def mode(n):
return statistics.mode(n)
while True:
print("1. Mean")
print("2. Median")
print("3. Mode")
ch = int(input("Enter your choice: "))
if ch==1:
n = input("Enter a list of numbers separated by spaces: ").split()
n= [float(n) for n in n]
print("Mean:", mean(n))
break
elif ch==2:
n= input("Enter a list of numbers separated by spaces: ").split()
n = [float(n) for n in n]
print("Median:", median(n))
break
elif ch==3:
n = input("Enter a list of numbers separated by spaces: ").split()
n = [float(n) for n in n]
print("Mode:", mode(n))
break
elif ch==0:
print("Exiting program.")
break
else:
print("Invalid choice.")

Output:
1. Calculate Mean
2. Calculate Median
3. Calculate Mode
Enter your choice: 1
Enter a list of numbers separated by spaces: 1 2 3 4
Mean: 2.5

1. Calculate Mean
2. Calculate Median 3. Calculate Mode
Enter your choice: 2
Enter a list of numbers separated by spaces: 1 2 4 5
Median: 3.0

1. Calculate Mean
2. Calculate Median3. Calculate Mode
Enter your choice: 3
Enter a list of numbers separated by spaces: 1 2 3 3
Mode: 3.0

1. Calculate Mean
2. Calculate Median
3. Calculate Mode
Enter your choice: 4

Invalid choice.

1. Calculate Mean
2. Calculate Median
3. Calculate Mode
Enter your choice: 0

Exiting program.

PROGRAM 6

Write a menu driven program to:


● Read the file line by line and print it.
● Count the number of vowels and consonants present in the text file.
● Count number of words in the file.
Source Code:

while True:
print("1. Read the file line by line and print it.")
print("2. Count the number of vowels and consonants present in the text
file.")
print("3. Count number of words in the file.")
ch = int(input("Enter your choice: "))
if ch == 1:
file = open("tech.txt", "r")
for line in file:
print(line)
print("\n")
file.close()
elif ch == 2:
file = open("tech.txt", "r")

content = file.read().lower()
vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
v = sum(1 for char in content if char in vowels)
c = sum(1 for char in content if char in consonants)
print("Number of vowels:", v)
print("Number of consonants:", c)
file.close()
elif ch == 3:
file = open("tech.txt", "r")
w = len(file.read().split())
print("Number of words:", w)
file.close()

elif==0:
print(“Exiting program”)
break
else:
print("Invalid choice.")

Output:

1. Read the file line by line and print it.


2. Count the number of vowels and consonants present in the text file.
3. Count number of words in the file.
Enter your choice: 1
Technology is the study of scientific knowledge in order to create tools and
processes that may be used to change the world by increasing efficiency in
nearly every aspect of our lives.
Technology has made our lives easier, and all human beings have become
entirely dependent on technology.

1. Read the file line by line and print it.


2. Count the number of vowels and consonants present in the text file.
3. Count number of words in the file.
Enter your choice: 2
Number of vowels: 92
Number of consonants: 148

1. Read the file line by line and print it.


2. Count the number of vowels and consonants present in the text file.
3. Count number of words in the file.
Enter your choice: 3
Number of words: 48
1. Read the file line by line and print it.
2. Count the number of vowels and consonants present in the text file.
3. Count number of words in the file.
Enter your choice: 4
Invalid choice.

1. Read the file line by line and print it.


2. Count the number of vowels and consonants present in the text file.
3. Count number of words in the file.
Enter your choice: 4
Exiting program.
PROGRAM 7

Write a menu driven program to


● Write those lines which have the character ‘p’ from one text file to
another text file.
● Display all line starting with ‘t’ or ‘T’.
● Display the last line of the text file.

Source code:

def fp(input_file, output_file):


inp = open(input_file, 'r')
out = open(output_file, 'w')
for i in inp.readlines():
if 'p' in i:
out.writelines
inp.close()
out.close()

while True:
print("1.Write those lines which have the character ‘p’ from one text
file to another text file.")
print("2. Display all line starting with ‘t’ or ‘T’.")
print("3. Display the last line of the text file.")
ch = int(input("Enter your choice: "))

if ch == 1:
input_file = "tech.txt"
output_file = "tech_p.txt"
fp(input_file, output_file)
print("Lines with 'p' written to :", output_file)
break
elif ch == 2:
f = open("tech.txt", 'r')
for line in f.readlines():
if line[0].lower() == 't':
print(line)
f.close()
break
elif ch == 3:
f = open("tech.txt", 'r')
lines = f.readlines()
if lines:
print(lines[-1])
f.close()
break
elif ch == 0:
print("Exiting program.")
break
else:
print("Invalid choice.")

Output:

1.Write those lines which have the character ‘p’ from one text file to another
text file.
2. Display all line starting with ‘t’ or ‘T’.
3. Display the last line of the text file.
Enter your choice: 1

Lines with 'p' written to : tech_p.txt

1.Write those lines which have the character ‘p’ from one text file to another
text file.
2. Display all line starting with ‘t’ or ‘T’.
3. Display the last line of the text file.
Enter your choice: 2
Technology is the study of scientific knowledge in order to create tools and
processes that may be used to change the world by increasing efficiency in
nearly every aspect of our lives.
Technology has made our lives easier, and all human beings have become
entirely dependent on technology.

1.Write those lines which have the character ‘p’ from one text file to another
text file.
2. Display all line starting with ‘t’ or ‘T’.
3. Display the last line of the text file.
Enter your choice: 3
Technology has made our lives easier, and all human beings have become
entirely dependent on technology.

1.Write those lines which have the character ‘p’ from one text file to another
text file.

2. Display all line starting with ‘t’ or ‘T’.


3. Display the last line of the text file.
Enter your choice: 4
Invalid choice.

1.Write those lines which have the character ‘p’ from one text file to another
text file.
2. Display all line starting with ‘t’ or ‘T’.
3. Display the last line of the text file.
Enter your choice: 0
Exiting program.
PROGRAM 8

Write a menu-driven program in Python to perform the following tasks.


● Append records to the file.
● Display all records from the file .
● Display details of employees with Salary > 15000.
● Search by Employee Number and Modify the salary.

Source Code:

while True:
import pickle
f=open("employee.dat",'rb+')
print("1.To append employee records to the file")
print("2.To display all records from the file")
print("3.to display details of employees with salary>15000")
print("4.Search by employee number and modify the salary")
print("Enter 0 to exit")
print()
ch=int(input("Enter your choice: "))
print()
if ch==1:
def rec():
n=int(input("Enter the number of employees: "))
rec=[]
for i in range(n):
eno=int(input("Enter employee number: "))
ename=input("Enter employee name: ")
des=input("Enter the employee designation: ")
sal=int(input("Enter the salary of the employee:"))
data=[eno,ename,des,sal]
rec.append(data)
print("Name appended into the file\n")
pickle.dump(rec,f)
rec()

elif ch==2:
def dis():
data=pickle.load(f)
print("ID
NO\t\t","NAME\t\t","DESIGNATION\t\t","SALARY\t\t")
for i in data:
for j in i:
print(j,end="\t\t")
print()
print()
dis()

elif ch==3:
def details():
data=pickle.load(f)
print("ID
NO\t\t","NAME\t\t","DESIGNATION\t\t","SALARY\t\t")
for i in data:
if i[3]>15000:
for j in i:
print(j,end="\t\t")
print()
print()
details()

elif ch==4:
def search():
data=pickle.load(f)
no=int(input("Enter the employee number whos salary has
to be modified: "))
for i in data:
if i[0]==no:
salary=int(input("Enter the new salary: "))
i[3]=salary
break
f.seek(0)
pickle.dump(data,f)
f.seek(0)
new=pickle.load(f)
print("Modified details")
print("ID
NO\t\t","NAME\t\t","DESIGNATION\t\t","SALARY\t\t")
for i in new:
for j in i:
print(j,end="\t\t")
print()
print()
search()

elif ch==0:
print("Exiting program.")
break
else:
print("Invalid choice.")
f.close()

Output:

1.To append employee records to the file

2.To display all records from the file

3.to display details of employees with salary>15000

4.Search by employee number and modify the salary

Enter 0 to exit

Enter your choice: 1

Enter the number of employees: 3

Enter employee number: 105


Enter employee name: Suresh

Enter the employee designation: Accountant

Enter the salary of the employee:13000

Name appended into the file

Enter employee number: 106

Enter employee name: Ramesh

Enter the employee designation: Manager

Enter the salary of the employee:25000

Name appended into the file

Enter employee number: 107

Enter employee name: Mukesh

Enter the employee designation: Director

Enter the salary of the employee:65000

Name appended into the file


1.To append employee records to the file

2.To display all records from the file

3.to display details of employees with salary>15000

4.Search by employee number and modify the salary

Enter 0 to exit

Enter your choice: 2

ID NO NAME DESIGNATION SALARY

105 Suresh Accountant 13000

106 Ramesh Manager 25000

107 Mukesh Director 65000

1.To append employee records to the file

2.To display all records from the file

3.to display details of employees with salary>15000


4.Search by employee number and modify the salary

Enter 0 to exit

Enter your choice: 3

ID NO NAME DESIGNATION SALARY

106 Ramesh Manager 25000

107 Mukesh Director 65000

1.To append employee records to the file

2.To display all records from the file

3.to display details of employees with salary>15000

4.Search by employee number and modify the salary

Enter 0 to exit

Enter your choice: 4


Enter the employee number whos salary has to be modified: 107

Enter the new salary: 60000

Modified details

ID NO NAME DESIGNATION SALARY

105 Suresh Accountant 13000

106 Ramesh Manager 25000

107 Mukesh Director 60000

1.To append employee records to the file

2.To display all records from the file

3.to display details of employees with salary>15000

4.Search by employee number and modify the salary

Enter 0 to exit

Enter your choice: 5


Invalid choice.

1.To append employee records to the file

2.To display all records from the file

3.to display details of employees with salary>15000

4.Search by employee number and modify the salary

Enter 0 to exit

Enter your choice: 0

Exiting program.

PROGRAM 9
The file ‘Book’ contains the following information: Book Number, Title of the
Book, Cost

Write a menu-driven program in Python to perform the following tasks:

● Append records to the file.


● Display all records from the file.
● Search by Book Number and display details.
● Increase cost of all books by 2%

PROGRAM 10
The file ‘Student’ contains the following information: Roll number,
Name and Marks

● Append records to the file.


● Search for a given roll number and display the name, if not
found display appropriate message.
● Input a roll number and update the marks.

PROGRAM 11
PROGRAM 16
To create a database ELECTRICITY with table EBILL, and write queries and
generate output of the following:

> create database ELECTRICITY;


> use ELECTRICITY;
> create table EBILL
-> (RR_NO varchar(10),
-> CON_NAME char(20),
-> DATE_EBILL date,
-> UNIT integer(10));
> INSERT INTO EBILL VALUES ('A11','Jothika','2020-10-02',224);
> INSERT INTO EBILL VALUES ('A12','Titas','2020-09-12',212);
> INSERT INTO EBILL VALUES ('A13','Ankan','2020-09-24',232);
> INSERT INTO EBILL VALUES ('A14','Deepak','2020-10-01',242);
l> INSERT INTO EBILL VALUES ('A15','Archana','2020-10-04',244);
> select * from EBILL;

1. Add new field to the table-Bill_amt of datatype decimal(10,2).


> alter table EBILL ADD(BILL_AMT decimal(10,2));
> desc ebill;

2. Compute the bill amount for each customer as MinAmt + 4.50 per unit
(MinAmt = 50)
> update EBILL SET BILL_AMT=UNIT*4.50+50;
3. Display Customer name and Bill Amount where Bill Amount > 1000.
> select CON_NAME,BILL_AMT from EBILL where
BILL_AMT>1000;

4. Display the min, max, sum and average of Unit.


> select min(UNIT),max(UNIT),sum(UNIT),avg(UNIT) from EBILL;

5. Display details of Customers whose name starts with ‘A’.


> select * from EBILL
-> where CON_NAME like 'A';
6. Display Bills generated in the month of October.
> select *
-> from EBILL
-> where month(DATE_EBILL)=10;

7. List all the bills generated in ascending order of Bill Date.


l> select *
-> from EBILL
-> order by DATE_EBILL asc;
SQL - 4. To create a database COMPANY with table EMPLOYEE in MySQL
&amp; create an API using Python Connectivity.

Write a menu driven program to

• ACCEPT new employee details and display all records.


• DISPLAY employee details by employee number; display appropriate
message if employee
• number not matched.
• UPDATE the Salary by employee number.
• DELETE Record by employee number.

Source code:
CREATE DATABASE COMPANY;
USE COMPANY;
CREATE TABLE EMPLOYEE (
empno INT PRIMARY KEY,
name VARCHAR(50),
dept VARCHAR(30),
salary INT
);
INSERT INTO EMPLOYEE (empno, name, dept, salary) VALUES
(1010, 'AMIT', 'SALES', 25000),
(1014, 'ABEL', 'IT', 32000),
(1021, 'NITIN', 'IT', 28000),
(1032, 'JAMES', 'ACCOUNTS', 16000);

import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="COMPANY"
)

cursor = db.cursor()

def accept_employee():
empno = int(input("Enter Employee Number: "))
name = input("Enter Name: ")
dept = input("Enter Department: ")
salary = int(input("Enter Salary: "))

cursor.execute("INSERT INTO EMPLOYEE (empno, name, dept, salary)


VALUES (%s, %s, %s, %s)",
(empno, name, dept, salary))
db.commit()
print("Employee added successfully.")

def display_all_employees():
cursor.execute("SELECT * FROM EMPLOYEE")
results = cursor.fetchall()
print("Employee Records:")
for row in results:
print(row)

def display_employee_by_number():
empno = int(input("Enter Employee Number to Display: "))
cursor.execute("SELECT * FROM EMPLOYEE WHERE empno = %s",
(empno,))
result = cursor.fetchone()
if result:
print(result)
else:
print("Employee not found.")
def update_salary():
empno = int(input("Enter Employee Number to Update Salary: "))
new_salary = int(input("Enter New Salary: "))
cursor.execute("UPDATE EMPLOYEE SET salary = %s WHERE empno
= %s", (new_salary, empno))
db.commit()
if cursor.rowcount > 0:
print("Salary updated successfully.")
else:
print("Employee not found.")

def delete_employee():
empno = int(input("Enter Employee Number to Delete: "))
cursor.execute("DELETE FROM EMPLOYEE WHERE empno = %s",
(empno,))
db.commit()
if cursor.rowcount > 0:
print("Employee deleted successfully.")
else:
print("Employee not found.")

def main_menu():
while True:
print("\nMenu:")
print("1. Accept New Employee and Display All Records")
print("2. Display Employee Details by Employee Number")
print("3. Update Salary by Employee Number")
print("4. Delete Record by Employee Number")
print("5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
accept_employee()
display_all_employees()
elif choice == 2:
display_employee_by_number()
elif choice == 3:
update_salary()
elif choice == 4:
delete_employee()
elif choice == 5:
break
else:
print("Invalid choice. Please try again.")
main_menu()
cursor.close()
db.close()

Output:
1. Accept New Employee and Display All Records
2. Display Employee Details by Employee Number
3. Update Salary by Employee Number
4. Delete Record by Employee Number
5. Exit
Enter your choice:

#choice 1
Enter Employee Number: 1040
Enter Name: SAMUEL
Enter Department: HR
Enter Salary: 35000

Employee added successfully.


Employee Records:
(1010, 'AMIT', 'SALES', 25000)
(1014, 'ABEL', 'IT', 32000)
(1021, 'NITIN', 'IT', 28000)
(1032, 'JAMES', 'ACCOUNTS', 16000)
(1040, 'SAMUEL', 'HR', 35000)

#choice 2
Enter Employee Number to Display: 1014
(1014, 'ABEL', 'IT', 32000)

#choice 3
Enter Employee Number to Update Salary: 1021
Enter New Salary: 30000

Salary updated successfully.

#choice 4
Enter Employee Number to Delete: 1032
Employee deleted successfully.

SQL - 5. To create a database ASSIGNMENT with table STUDENT in


MySQL &amp; create an API using Python Connectivity.

Write the menu driven program to :

• ADD New Records


• DISPLAY BY Status of Assignment
• Search by Roll No and UPDATE Status of Assignment
• Search by Roll No and DELETE Student Record
• DISPLAY ALL Records

Source code:
CREATE DATABASE ASSIGNMENT;
USE ASSIGNMENT;
CREATE TABLE STUDENT (
ROLLNO INT PRIMARY KEY,
NAME VARCHAR(50),
PERCENTAGE FLOAT,
SECTION CHAR(1),
ASSIGNMENT VARCHAR(20))
INSERT INTO STUDENT (ROLLNO, NAME, PERCENTAGE, SECTION,
ASSIGNMENT) VALUES
(103, 'RUHANI', 76.8, 'A', 'PENDING'),
(104, 'GEORGE', 71.2, 'A', 'SUBMITTED'),
(105, 'SIMRAN', 81.2, 'B', 'EVALUATED'),
(107, 'AHAMED', 61.2, 'C', 'PENDING'),
(108, 'RAUNAK', 32.5, 'B', 'SUBMITTED');

import mysql.connector
def connect():
return mysql.connector.connect(
host="localhost",
user="root",
passwd="12345",
database="ASSIGNMENT"
)

def newRec():
c = connect()
cursor = c.cursor()
roll = int(input("Enter Roll No: "))
name = input("Enter Name: ")
prcnt = float(input("Enter Percentage: "))
sec = input("Enter Section: ")
assStat = input("Enter Assignment Status: ")
cursor.execute(
"INSERT INTO STUDENT (ROLLNO, NAME, PERCENTAGE,
SECTION, ASSIGNMENT) VALUES (%s, %s, %s, %s, %s)",
(roll, name, prcnt, sec, assStat)
)
c.commit()
cursor.close()
c.close()
print("Student added successfully.")

def DisplayBy():
c = connect()
cursor = c.cursor()
state = input("Enter Status of Assignment: ")
cursor.execute("SELECT * FROM STUDENT WHERE ASSIGNMENT
= %s", (state,))
for i in cursor.fetchall():
print(i)
cursor.close()
c.close()

def AssignStatUpdate():
c = connect()
cursor = c.cursor()
roll = int(input("Enter Roll No to update: "))
updatedAssign = input("Enter your updated assignment status: ")
cursor.execute(
"UPDATE STUDENT SET ASSIGNMENT = %s WHERE ROLLNO
= %s",
(updatedAssign, roll)
)
c.commit() # Commit the update
cursor.close()
c.close()
print("Assignment status updated.")

def DeleteByRow():
c = connect()
cursor = c.cursor()
roll = int(input("Enter Roll No to delete: "))
cursor.execute("DELETE FROM STUDENT WHERE ROLLNO = %s",
(roll,))
c.commit()
cursor.close()
c.close()
print("Record deleted.")

def Display():
c = connect()
cursor = c.cursor()
cursor.execute("SELECT * FROM STUDENT")
for i in cursor.fetchall():
print(i)
cursor.close()
c.close()

while True:
print("""
MENU
1. ADD New Records
2. DISPLAY BY Status of Assignment
3. Search by Roll No and UPDATE Status of Assignment
4. Search by Roll No and DELETE Student Record
5. DISPLAY ALL Records
6. EXIT
""")
choice = int(input("Enter your choice: "))
if choice == 1:
newRec()
elif choice == 2:
DisplayBy()
elif choice == 3:
AssignStatUpdate()
elif choice == 4:
DeleteByRow()
elif choice == 5:
Display()
elif choice == 6:
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")

Output:
1. Add New Records
2. Display Records by Assignment Status
3. Search by Roll No and Update Assignment Status
4. Search by Roll No and Delete Student Record
5. Display All Records
6. Exit
#choice 1
Enter Roll No: 109
Enter Name: John
Enter Percentage: 85.3
Enter Section: B
Enter Assignment Status: PENDING
Student added successfully.

#choice 2
Enter Status of Assignment: PENDING
(103, 'RUHANI', 76.8, 'A', 'PENDING')
(107, 'AHAMED', 61.2, 'C', 'PENDING')
(109, 'John', 85.3, 'B', 'PENDING')

#choice 3
Enter Roll No to update: 109
Enter your updated assignment status: SUBMITTED
Assignment status updated.
#choice 4
Enter Roll No to delete: 109
Record deleted.

#choice 5
(103, 'RUHANI', 76.8, 'A', 'PENDING')
(104, 'GEORGE', 71.2, 'A', 'SUBMITTED')
(105, 'SIMRAN', 81.2, 'B', 'EVALUATED')
(107, 'AHAMED', 61.2, 'C', 'PENDING')
(108, 'RAUNAK', 32.5, 'B', 'SUBMITTED')

SQL – 6. Create a table CAR with the following details.

Design a menu driven API using Python Connectivity to:

• ACCEPT new employee details and DISPLAY all records.


• DISPLAY car details as per user input. Also display appropriate message if
car number is not
• matched.
• UPDATE the Charge by car number
• DELETE Record by car number.

Source code:
CREATE TABLE CAR ( CCODE INT PRIMARY KEY, CNAME
VARCHAR(50), COMPANY VARCHAR(50), COLOUR VARCHAR(20),
CAPACITY INT, CHARGE INT );
INSERT INTO CAR (CCODE, CNAME, COMPANY, COLOUR,
CAPACITY, CHARGE) VALUES
(501, 'A-Star', 'Suzuki', 'RED', 3, 140),
(502, 'Innova', 'Toyota', 'WHITE', 7, 300),
(503, 'Indigo', 'Tata', 'SILVER', 3, 120),
(509, 'SX4', 'Suzuki', 'SILVER', 4, 200),
(510, 'C Class', 'Mercedes', 'RED', 4, 450);

import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="12345",
database="CAR"
)

mycursor = mydb.cursor()
def acceptNdisplay():
CODE = int(input("Enter CCODE: "))
NAME = input("Enter CNAME: ")
COMP = input("Enter COMPANY: ")
COLOR = input("Enter COLOUR: ")
CAP = int(input("Enter CAPACITY: "))
CHARGE = float(input("Enter CHARGE: "))

mycursor.execute(
"INSERT INTO CAR (CCODE, CNAME, COMPANY, COLOUR,
CAPACITY, CHARGE) VALUES (%s, %s, %s, %s, %s, %s)",
(CODE, NAME, COMP, COLOR, CAP, CHARGE)
)
mydb.commit()
print("Record added successfully!")
mycursor.execute("SELECT * FROM CAR")
records = mycursor.fetchall()
for record in records:
print(record)

def carDetails():
CCODE = int(input("Enter CCODE to search: "))
mycursor.execute("SELECT * FROM CAR WHERE CCODE = %s",
(CCODE,))
record = mycursor.fetchone()
if record:
print(record)
else:
print("No car found with the given CCODE.")

def updateCharge():
CCODE = int(input("Enter CCODE to update: "))
mycursor.execute("SELECT * FROM CAR WHERE CCODE = %s",
(CCODE,))
record = mycursor.fetchone()
if record:
new_charge = float(input("Enter new CHARGE: "))
mycursor.execute("UPDATE CAR SET CHARGE = %s WHERE
CCODE = %s", (new_charge, CCODE))
mydb.commit()
print("CHARGE updated successfully!")
else:
print("No car found with the given CCODE.")

def deleteRec():
CCODE = int(input("Enter CCODE to delete: "))
mycursor.execute("SELECT * FROM CAR WHERE CCODE = %s",
(CCODE,))
record = mycursor.fetchone()
if record:
mycursor.execute("DELETE FROM CAR WHERE CCODE = %s",
(CCODE,))
mydb.commit()
print("Record deleted successfully!")
else:
print("No car found with the given CCODE.")

print('''To:
ACCEPT new employee details and DISPLAY all records - INPUT1
DISPLAY car details as per user input. Also display appropriate message if car
number is not matched - INPUT 2
UPDATE the Charge by car number - INPUT 3
DELETE Record by car number - INPUT 4
Exit - INPUT-0 ''')
choice=int(input("Enter your choice: "))
if choice==1:
acceptNdisplay()
elif choice==2:
carDetails()
elif choice==3:
updateCharge()
elif choice==4:
deleteRec()
elif choice==0:
print("Exited.")
else:
print("INVALID CHOICE.")

mycursor.close()
mydb.close()

Output:
ACCEPT new employee details and DISPLAY all records - INPUT1
DISPLAY car details as per user input. Also display appropriate message if car
number is not matched - INPUT 2
UPDATE the Charge by car number - INPUT 3
DELETE Record by car number - INPUT 4
Exit - INPUT-0
Enter your choice:

#choice 1
Enter CCODE: 511 Enter CNAME: Swift
Enter COMPANY: Suzuki
Enter COLOUR: BLUE
Enter CAPACITY: 5
Enter CHARGE: 150

Record added successfully!


(501, 'A-Star', 'Suzuki', 'RED', 3, 140)
(502, 'Innova', 'Toyota', 'WHITE', 7, 300)
(503, 'Indigo', 'Tata', 'SILVER', 3, 120)
(509, 'SX4', 'Suzuki', 'SILVER', 4, 200)
(510, 'C Class', 'Mercedes', 'RED', 4, 450)
(511, 'Swift', 'Suzuki', 'BLUE', 5, 150)

#choice 2
Enter CCODE to search: 503
(503, 'Indigo', 'Tata', 'SILVER', 3, 120)

Enter CCODE to search: 515


No car found with the given CCODE.

#choice 3
Enter CCODE to update: 509 Enter new CHARGE: 220
CHARGE updated successfully!

#choice 4
Enter CCODE to delete: 503
Record deleted successfully!

SQL - 7. Create a table TEACHER in MySQL.


Design a menu driven API using Python Connectivity to:

• ACCEPT new details.


• SEARCH by TID and DISPLAY details
• UPDATE records
• DELETE Record

Source code:
CREATE DATABASE School;
USE School;
CREATE TABLE TEACHER (
tid INT PRIMARY KEY,
name VARCHAR(50),
deptid INT,
age INT,
salary INT,
gender CHAR(1));
INSERT INTO TEACHER (tid, name, deptid, age, salary, gender)
VALUES
(1, 'JUGAL', 103, 34, 12000, 'M'),
(2, 'SHARMILLA', 101, 31, 20000, 'F'),
(3, 'SANDEEP', 102, 32, 30000, 'M'),
(4, 'SANGEETA', 102, 42, 25000, 'F'),
(5, 'RAKESH', 101, 50, 15000, 'M'),
(6, 'SHYAM', 101, 50, 15000, 'M'),
(7, 'SHIVA', 102, 44, 20000, 'M'),
(8, 'SHILPA', 102, 40, 20000, 'F');
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="12345",
database="School"
)
mycursor = connection.cursor()

def accept_details():
tid = int(input("Enter Teacher ID: "))
name = input("Enter Name: ")
deptid = int(input("Enter Department ID: "))
age = int(input("Enter Age: "))
salary = int(input("Enter Salary: "))
gender = input("Enter Gender (M/F): ")
mycursor.execute(
"INSERT INTO TEACHER (tid, name, deptid, age, salary, gender)
VALUES (%s, %s, %s, %s, %s, %s)",
(tid, name, deptid, age, salary, gender)
)
connection.commit()
print("New teacher details added successfully.")

def search_by_tid():
tid = int(input("Enter Teacher ID to search: "))
cursor.execute("SELECT * FROM TEACHER WHERE tid = %s", (tid,))
result = mycursor.fetchone()
if result:
print("Record Found:", result)
else:
print("No record found with the given TID.")

def update_record():
tid = int(input("Enter Teacher ID to update: "))
column = input("Enter column to update (name/deptid/age/salary/gender): ")
new_value = input("Enter new value: ")
mycursor.execute(f"UPDATE TEACHER SET {column} = %s WHERE tid
= %s", (new_value, tid))
connection.commit()
print("Record updated successfully.")

def delete_record():
tid = int(input("Enter Teacher ID to delete: "))
mycursor.execute("DELETE FROM TEACHER WHERE tid = %s", (tid,))
connection.commit()
print("Record deleted successfully.")

def main_menu():
while True:
print("Menu:")
print("1. Accept New Details")
print("2. Search by TID and Display Details")
print("3. Update Records")
print("4. Delete Record")
print("5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
accept_details()
elif choice == 2:
search_by_tid()
elif choice == 3:
update_record()
elif choice == 4:
delete_record()
elif choice == 5:
print("Exiting...")
break
else:
print("Invalid choice. Try again.")
main_menu()
cursor.close()
connection.close()

Output:
Menu:
1. Accept New Details
2. Search by TID and Display Details
3. Update Records
4. Delete Record
5. Exit
Enter your choice:
Enter your choice: 1
Enter Teacher ID: 9
Enter Name: ANITA
Enter Department ID: 101
Enter Age: 35
Enter Salary: 22000
Enter Gender (M/F): F
New teacher details added successfully.

Enter your choice: 2


Enter Teacher ID to search: 3
Record Found: (3, 'SANDEEP', 102, 32, 30000, 'M')
Enter your choice: 3
Enter Teacher ID to update: 3
Enter column to update (name/deptid/age/salary/gender): salary
Enter new value: 35000
Record updated successfully.

Enter your choice: 4


Enter Teacher ID to delete: 9
Record deleted successfully.

You might also like