Connectivity
Q1. Write a complete menu driven program to :
Create a database school and define the following functions to implement python mysql
connectivity :
1. CREATE_DATABASE()
2. SHOW_ DATABASES()
3. CREATE_TABLE()
4. SHOW_TABLES()
5. INSERT()
6. DESCRIBE()
7. SELECT*()
TO BE IMPLEMENTED ON STUDENT TABLE. PUT 5 RECORDS AS SAMPLE DATA
Sol:-
Input:-
#Q1
import [Link] as m
mydb=[Link](host='localhost',user='root',passwd='aarush1')
c=[Link]()
#[Link]("CREATE DATABASE school")
#[Link]("CREATE TABLE student(Rollno int PRIMARY KEY, Name varchar(15), age
int, class varchar(15))")
def createdb():
print("Database school created")
def showdb():
[Link]('SHOW DATABASES')
print("DATABASES:")
for i in c:
print(i)
def create_table():
print("Table student created")
def show_table():
[Link]("USE school")
[Link]("SHOW TABLES")
print("TABLES:")
for i in c:
print(i)
def desc_table():
[Link]("USE school")
[Link]("DESC student")
for i in c:
print(i)
def insert():
[Link]("USE school")
n=int(input("Enter no of records: "))
for i in range(n):
print("Entering record", i+1)
r = int(input("Enter Roll No: "))
n = input("Enter Name: ")
a = int(input("Enter Age: "))
cl = input("Enter Class: ")
val = (r, n, a, cl)
query = "INSERT INTO student(Rollno, Name, age, class) VALUES(%s, %s, %s, %s)"
[Link](query, val)
[Link]()
print("Records inserted successfully")
def select_all():
[Link]("USE school")
[Link]("SELECT * FROM student")
res=[Link]()
for i in res:
print(i)
while True:
print("=== SCHOOL DATABASE MENU ===")
print("1. Create Database\n2. Show Databases\n3. Create Table\n4. Show Tables\n5. Insert
Records\n6. Describe Table\n7. Select All Records\n8. Exit")
ch=input("Enter choice: ")
if ch=='1':
createdb()
elif ch=='2':
showdb()
elif ch=='3':
create_table()
elif ch=='4':
show_table()
elif ch=='5':
insert()
elif ch=='6':
desc_table()
elif ch=='7':
select_all()
elif ch=='8':
[Link]()
print("Exiting...")
break
else:
print("invalid input,try again!!")
Output:-
Q2. WAP in python to create a table EMPLOYEE in mysql with fields
EMP_CODE, NAME, AGE, INCOME and insert values in the table.
• • Using mysql connectivity increase the salary of the employees whose
salaries>50000
• Display all the records in ascending order of their salary
Sol:-
Input:-
#Q2
import [Link] as m
mydb = [Link](host='localhost', user='root', passwd='aarush1')
c = [Link]()
#[Link]("CREATE DATABASE company")
#[Link]("CREATE TABLE EMPLOYEE(EMP_CODE int PRIMARY KEY,
NAME varchar(15), AGE int, INCOME float)")
[Link]("USE company")
def insert():
n = int(input("Enter no of records: "))
for i in range(n):
print("Entering record", i + 1)
ec = int(input("Enter EMP_CODE: "))
nm = input("Enter Name: ")
ag = int(input("Enter Age: "))
inc = float(input("Enter Income: "))
val = (ec, nm, ag, inc)
query = "INSERT INTO EMPLOYEE(EMP_CODE, NAME, AGE,
INCOME) VALUES(%s, %s, %s, %s)"
[Link](query, val)
[Link]()
print("Records inserted successfully")
def update_salary():
inc_amt = float(input("Enter the amount to increase: "))
query = "UPDATE EMPLOYEE SET INCOME = INCOME + %s WHERE
INCOME > 50000"
[Link](query, (inc_amt,))
[Link]()
print("Salaries updated for", [Link], "employees")
def display_sorted():
print("RECORDS (Sorted by Salary):")
[Link]("SELECT * FROM EMPLOYEE ORDER BY INCOME ASC")
res = [Link]()
for i in res:
print(i)
while True:
print("=== EMPLOYEE MANAGEMENT MENU ===")
print("1. Insert Records\n2. Increase Salary\n3. Display Records (Ascending
Order)\n4. Exit")
ch = input("Enter choice: ")
if ch == '1':
insert()
elif ch == '2':
update_salary()
elif ch == '3':
display_sorted()
elif ch == '4':
[Link]()
print("Exiting...")
break
else:
print("invalid input,try again!!")
OUTPUT:-
Q3. WAP in python to create a table EMPLOYEE in mysql with fields
EMP_CODE, NAME, AGE, INCOME and insert values in the table.
• Delete the record whose name is read from the keyboard at execution time
• • Search for the record of an employee by inputting his/her name from the
user and if it exists display the record.
Sol:-
Input:-
#Q3
import [Link] as m
mydb = [Link](host='localhost', user='root', passwd='aarush1')
c = [Link]()
#[Link]("CREATE DATABASE company")
#[Link]("CREATE TABLE EMPLOYEE(EMP_CODE int PRIMARY KEY,
NAME varchar(15), AGE int, INCOME float)")
[Link]("USE company")
def insert():
n = int(input("Enter no of records: "))
for i in range(n):
print("Entering record", i + 1)
ec = int(input("Enter EMP_CODE: "))
name = input("Enter Name: ")
age = int(input("Enter Age: "))
inc = float(input("Enter Income: "))
val = (ec, name, age, inc)
query = "INSERT INTO EMPLOYEE(EMP_CODE, NAME, AGE,
INCOME) VALUES(%s, %s, %s, %s)"
[Link](query, val)
[Link]()
print("Records inserted successfully")
def delete_record():
name = input("Enter Name to delete: ")
query = "DELETE FROM EMPLOYEE WHERE NAME = %s"
[Link](query, (name,))
[Link]()
if [Link] > 0:
print("Record deleted successfully")
else:
print("No record found with that name")
def search_record():
name = input("Enter Name to search: ")
query = "SELECT * FROM EMPLOYEE WHERE NAME = %s"
[Link](query, (name,))
res = [Link]()
if res:
print("Record Found:", res)
else:
print("Record does not exist")
def table_rec():
[Link]("SELECT * FROM EMPLOYEE")
res=[Link]()
for i in res:
print(i)
while True:
print("=== EMPLOYEE MANAGEMENT MENU ===")
print("1. Insert Records\n2. Delete Record\n3. Search Record\n4. table
records\[Link]")
ch = input("Enter choice: ")
if ch == '1':
insert()
elif ch == '2':
delete_record()
elif ch == '3':
search_record()
elif ch=='4':
table_rec()
elif ch == '5':
[Link]()
print("Exiting...")
break
else:
print("invalid input,try again!!")
OUTPUT:-
Q4. CONSIDER THE CODE GIVEN BELOW:
import [Link]
db=[Link].
,→connect(host="localhost",user="root",password="tiger",port=3406)
c=[Link]()
[Link]("use emp")
[Link]("create table emp(eno int primary key ,name char(20),sal float,dept␣
,→char(10))")
[Link]()
NOW, DEFINE ALL THESE FUNCTIONS
1. Add record
2. display all records
3. update a record
4. delete a record
5. search for a record
6. Quit
TAKE INPUTS FROM THE USER AT RUN TIME.
Sol:-
Input:-
#Q4
import [Link] as m
mydb = [Link](host='localhost', user='root', password='aarush1')
c = [Link]()
[Link]("CREATE DATABASE industry")
[Link]("USE industry")
[Link]("CREATE TABLE emp(EMP_CODE int PRIMARY KEY, NAME varchar(15),
sal int, dept varchar(20))")
def insert():
n = int(input("Enter no of records: "))
for i in range(n):
print("Entering record", i + 1)
eno = int(input("Enter EMP_CODE: "))
name = input("Enter name: ")
sal = float(input("Enter sal: "))
dept = input("Enter dept: ")
val = (eno, name, sal, dept)
query = "INSERT INTO emp(EMP_CODE, NAME, sal, dept)
VALUES(%s, %s, %s, %s)"
[Link](query, val)
[Link]()
print("Records inserted successfully")
def table_rec():
[Link]("SELECT * FROM emp")
res = [Link]()
for i in res:
print(i)
def update_record():
eno = int(input("Enter EMP_CODE to update salary: "))
new_sal = float(input("Enter new salary: "))
query = "UPDATE emp SET sal = %s WHERE EMP_CODE = %s"
[Link](query, (new_sal, eno))
[Link]()
if [Link] > 0:
print("Record updated successfully")
else:
print("Record not found")
def delete_record():
eno = int(input("Enter EMP_CODE to delete: "))
query = "DELETE FROM emp WHERE EMP_CODE = %s"
[Link](query, (eno,))
[Link]()
if [Link] > 0:
print("Record deleted successfully")
else:
print("No record found with that EMP_CODE")
def search_record():
eno = int(input("Enter EMP_CODE to search: "))
query = "SELECT * FROM emp WHERE EMP_CODE = %s"
[Link](query, (eno,))
res = [Link]()
if res:
print("Record Found:", res)
else:
print("Record does not exist")
while True:
print("=== EMPLOYEE MANAGEMENT MENU ===")
print("1. Add record")
print("2. display all records")
print("3. update a record")
print("4. delete a record")
print("5. search for a record")
print("6. EXIT")
ch = input("Enter choice: ")
if ch == '1':
insert()
elif ch == '2':
table_rec()
elif ch == '3':
update_record()
elif ch == '4':
delete_record()
elif ch == '5':
search_record()
elif ch == '6':
[Link]()
print("Exiting...")
break
else:
print("invalid input, try again!!")
OUTPUT:-
Q5. WAP to do following functions using python-mysql connectivity with
proper comments and user defined methods for the program file:
1) To create a database (name should be taken from the user)
2) To create a basic table (name and structure should be taken from the user)
Structure must contain: constraints and all types of data types of mysql.
3) Describe the table just created
4) Insert values taken from the user. (minimum 5 rows) 5) Show the usage of
aggregate functions .
6) perform alter table command(any 2 variations ) .
7) use update command
8) close and clean up the environment
SOL:-
INPUT:-
#Q5
import [Link] as m
mydb = [Link](host='localhost', user='root', password='aarush1')
c = [Link]()
def create_db():
name = input("Enter the name for your new database: ")
[Link]("CREATE DATABASE " + name)
[Link]("USE " + name)
print("Database " + name + " created and selected.")
def create_tbl():
t = input("Enter table name: ")
s = input("Enter columns and constraints: ")
[Link]("CREATE TABLE " + t + "(" + s + ")")
print("Table " + t + " created successfully.")
def desc_tbl():
t = input("Enter table name to describe: ")
[Link]("DESC " + t)
print("Structure of " + t + ":")
for row in [Link]():
print(row)
def insert_records():
t = input("Enter table name: ")
n = int(input("No of records: "))
[Link]("DESC " + t)
cols = [Link]()
p_str = ""
for i in range(len(cols)):
p_str = p_str + "%s"
if i < len(cols) - 1:
p_str = p_str + ","
q = "INSERT INTO " + t + " VALUES (" + p_str + ")"
for i in range(n):
print('no of record', i+1)
data = []
for col in cols:
val = input("Enter " + col[0] + ": ")
[Link](val)
[Link](q, tuple(data))
[Link]()
print(str(n) + " records inserted.")
def aggregate_funcs():
t = input("Enter table name: ")
col = input("Enter a numeric column for math operations: ")
print("Usage of Aggregate Functions:")
funcs = ["SUM", "AVG", "MAX", "MIN", "COUNT"]
for f in funcs:
[Link]("SELECT " + f + "(" + col + ") FROM " + t)
res = [Link]()
print(f + " of " + col + " is: " + str(res[0]))
def alter_table():
t = input("Enter table name: ")
new_col = input("Enter new column name to add: ")
[Link]("ALTER TABLE " + t + " ADD " + new_col + " VARCHAR(30)")
mod_col = input("Enter column name to change to INT type: ")
[Link]("ALTER TABLE " + t + " MODIFY " + mod_col + " INT")
print("Table altered successfully.")
def update_data():
t = input("Enter table name: ")
col = input("Which column do you want to update? ")
val = input("Enter the new value: ")
wh_col = input("Enter the condition column (e.g., id): ")
wh_val = input("Enter the condition value: ")
q = "UPDATE " + t + " SET " + col + " = %s WHERE " + wh_col + " = %s"
[Link](q, (val, wh_val))
[Link]()
print("Record updated.")
while True:
print("====== MYSQL PYTHON CONNECTIVITY MENU =====")
print("1. Create Database")
print("2. Create Table")
print("3. Describe Table")
print("4. Insert Records")
print("5. Use Aggregate Functions")
print("6. Alter Table (2 Variations)")
print("7. Update Record")
print("8. Exit and Cleanup")
choice = input("Enter your choice: ")
if choice == '1':
create_db()
elif choice == '2':
create_tbl()
elif choice == '3':
desc_tbl()
elif choice == '4':
insert_records()
elif choice == '5':
aggregate_funcs()
elif choice == '6':
alter_table()
elif choice == '7':
update_data()
elif choice == '8':
[Link]()
[Link]()
print("EXITING...")
break
else:
print("Invalid choice, please try again.")
OUTPUT:-