QUESTIONS ON MYSQL-DBMS and PYTHON CONNECTIVITY WITH ANSWERS USING
format()
Q1. Write a Python program to insert a new employee’s record into the Employee table. Take
Cname (name of the employee) and CId (ID of the employee) as inputs from the user.
Answer:
import mysql.connector
# Establish connection to the database
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="company"
)
cursor = mydb.cursor()
# Taking user inputs
Cname = input("Enter Employee Name: ")
CId = int(input("Enter Employee ID: "))
# Inserting data into the Employee table
query = "INSERT INTO Employee (Cname, CId) VALUES ('{}', {})".format(Cname, CId)
cursor.execute(query)
# Commit changes
mydb.commit()
print("Record inserted successfully.")
Q2. Write a Python program to update the name of an employee in the Employee table
based on their CId. Take inputs for CId and the new Cname from the user.
Answer:
import mysql.connector
# Establish connection to the database
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="company"
)
cursor = mydb.cursor()
# Taking user inputs
CId = int(input("Enter Employee ID to update: "))
Cname = input("Enter new Employee Name: ")
# Updating the Employee table
query = "UPDATE Employee SET Cname = '{}' WHERE CId = {}".format(Cname, CId)
cursor.execute(query)
# Commit changes
mydb.commit()
print("Record updated successfully.")
---
Q3. Write a Python program to delete an employee's record from the Employee table using
their CId. Take CId as input from the user.
Answer:
import mysql.connector
# Establish connection to the database
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="company"
)
cursor = mydb.cursor()
# Taking user input
CId = int(input("Enter Employee ID to delete: "))
# Deleting data from the Employee table
query = "DELETE FROM Employee WHERE CId = {}".format(CId)
cursor.execute(query)
# Commit changes
mydb.commit()
print("Record deleted successfully.")
---
Q4. Write a Python program to insert multiple employee records into the Employee table
using user inputs.
Answer:
import mysql.connector
# Establish connection to the database
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="company"
)
cursor = mydb.cursor()
# Taking user input for the number of records
n = int(input("Enter the number of records to insert: "))
for _ in range(n):
Cname = input("Enter Employee Name: ")
CId = int(input("Enter Employee ID: "))
query = "INSERT INTO Employee (Cname, CId) VALUES ('{}', {})".format(Cname, CId)
cursor.execute(query)
# Commit changes
mydb.commit()
print("Records inserted successfully.")