CS project final
CS project final
CERTIFICATE
This is to certify that the Computer science project report titled EMPLOYEE
MANAGEMENT SYSTEM which has been submitted to SUGUNA PIP School,
meeting the requirements of the CBSE Board practical examination for the academic
year 2024 – 2025, is a bonafide work done by Anvesh Narayan
I would also like to thank my Faculty Guide, NITHIYA R, for her valuable
mentoring throughout the project. The interesting lectures of my knowledge able
teacher have helped me understand the various concepts related to and see their
presence in the actual world.
School ID No : 6510
Register No. :
Class : XII – A4
Date of submission :
ABSTRACT
1. Introduction
2. Source code
3. Output
5. Conclusion
6. Bibliography
INTRODUCTION
import mysql.connector
from datetime import datetime
# Connect to MySQL Database
def connect_to_database():
"""
Connect to MySQL Database and return the connection object.
"""
try:
connection = mysql.connector.connect(
host="localhost", # Update as per your database config
user="root", # Your MySQL username
password="12345678", # Your MySQL password
database="employee_management" # The database name
)
print("Connected to the database!")
return connection
except mysql.connector.Error as err:
print(f"Error: {err}")
return None
# Create Employee Table
def create_employee_table(connection):
"""
Creates the employee table if it does not already exist in the database.
"""
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS employees (
employee_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
position VARCHAR(50),
salary DECIMAL(10, 2),
attendance INT,
department VARCHAR(50),
date_of_joining DATE
)
""")
connection.commit()
print("Employee table created successfully!")
# Function to add a new employee
def add_employee(connection):
"""
Add a new employee to the employees table.
"""
name = input("Enter name: ")
position = input("Enter position: ")
salary = float(input("Enter salary: "))
attendance = int(input("Enter attendance: "))
department = input("Enter department: ")
date_of_joining = input("Enter date of joining (YYYY-MM-DD): ")
cursor = connection.cursor()
query = "INSERT INTO employees (name, position, salary, attendance,
department, date_of_joining) VALUES (%s, %s, %s, %s, %s, %s)"
cursor.execute(query, (name, position, salary, attendance, department,
date_of_joining))
connection.commit()
print("Employee added successfully!")
# Function to view all employees
def view_employees(connection):
"""
Retrieve and display all employee records from the database.
"""
cursor = connection.cursor()
cursor.execute("SELECT * FROM employees")
results = cursor.fetchall()
for row in results:
print(row)
# Function to search employee by name
def search_employee_by_name(connection):
"""
Search for employees by their name.
"""
name = input("Enter name to search: ")
cursor = connection.cursor()
query = "SELECT * FROM employees WHERE name LIKE %s"
cursor.execute(query, (f"%{name}%",))
results = cursor.fetchall()
if results:
for row in results:
print(row)
else:
print("No employee found with that name.")
# Function to filter employees by position
def filter_employees_by_position(connection):
"""
Retrieve employees based on their position.
"""
position = input("Enter position to filter by: ")
cursor = connection.cursor()
query = "SELECT * FROM employees WHERE position = %s"
cursor.execute(query, (position,))
results = cursor.fetchall()
if results:
for row in results:
print(row)
else:
print(f"No employees found with the position: {position}")
# Function to update employee details
def update_employee(connection):
"""
Update details of an employee using their employee_id.
"""
employee_id = int(input("Enter employee ID to update: "))
name = input("Enter new name (leave blank to keep current): ")
position = input("Enter new position (leave blank to keep current): ")
salary = input("Enter new salary (leave blank to keep current): ")
attendance = input("Enter new attendance (leave blank to keep current):
")
department = input("Enter new department (leave blank to keep current):
")
cursor = connection.cursor()
updates = []
values = []
# Collect fields to update
if name:
updates.append("name = %s")
values.append(name)
if position:
updates.append("position = %s")
values.append(position)
if salary:
updates.append("salary = %s")
values.append(float(salary))
if attendance:
updates.append("attendance = %s")
values.append(int(attendance))
if department:
updates.append("department = %s")
values.append(department)
# Only proceed if there are fields to update
if updates:
query = f"UPDATE employees SET {', '.join(updates)} WHERE
employee_id = %s"
values.append(employee_id)
cursor.execute(query, values)
connection.commit()
print("Employee updated successfully!")
else:
print("No updates made.")
# Function to delete an employee
def delete_employee(connection):
"""
Delete an employee record based on their employee_id.
"""
employee_id = int(input("Enter employee ID to delete: "))
cursor = connection.cursor()
query = "DELETE FROM employees WHERE employee_id = %s"
cursor.execute(query, (employee_id,))
connection.commit()
print("Employee deleted successfully!")
# Function to view employees sorted by salary
def view_employees_by_salary(connection):
"""
Display all employees sorted by their salary.
"""
cursor = connection.cursor()
cursor.execute("SELECT * FROM employees ORDER BY salary
DESC")
results = cursor.fetchall()
for row in results:
print(row)
# Function to generate payroll report (total salary cost)
def generate_payroll_report(connection):
"""
Calculate and display the total salary cost of all employees.
"""
cursor = connection.cursor()
cursor.execute("SELECT SUM(salary) FROM employees")
total_salary = cursor.fetchone()[0]
print(f"Total Salary Cost for all employees: ${total_salary:.2f}")
# Function to generate average salary report
def generate_average_salary_report(connection):
"""
Calculate and display the average salary of employees.
"""
cursor = connection.cursor()
cursor.execute("SELECT AVG(salary) FROM employees")
avg_salary = cursor.fetchone()[0]
print(f"Average Salary of employees: ${avg_salary:.2f}")
# Function to display employees by department
def get_employees_by_department(connection):
"""
Display employees based on their department.
"""
department = input("Enter department to filter by: ")
cursor = connection.cursor()
query = "SELECT * FROM employees WHERE department = %s"
cursor.execute(query, (department,))
results = cursor.fetchall()
for row in results:
print(row)
# Function to view employees within a joining date range
def view_employees_by_date_range(connection):
"""
Display employees who joined within a specified date range.
"""
start_date = input("Enter start date (YYYY-MM-DD): ")
end_date = input("Enter end date (YYYY-MM-DD): ")
cursor = connection.cursor()
query = "SELECT * FROM employees WHERE date_of_joining
BETWEEN %s AND %s"
cursor.execute(query, (start_date, end_date))
results = cursor.fetchall()
for row in results:
print(row)
# Main menu function
def main():
connection = connect_to_database()
if connection:
create_employee_table(connection)
while True:
print("\nEmployee Management System")
print("1. Add Employee")
print("2. View All Employees")
print("3. Search Employee by Name")
print("4. Filter Employees by Position")
print("5. Update Employee Details")
print("6. Delete Employee")
print("7. View Employees by Salary")
print("8. Generate Payroll Report")
print("9. Generate Average Salary Report")
print("10. Get Employees by Department")
print("11. View Employees by Joining Date Range")
print("12. Exit")
choice = input("Enter choice: ")
if choice == '1':
add_employee(connection)
elif choice == '2':
view_employees(connection)
elif choice == '3':
search_employee_by_name(connection)
elif choice == '4':
filter_employees_by_position(connection)
elif choice == '5':
update_employee(connection)
elif choice == '6':
delete_employee(connection)
elif choice == '7':
view_employees_by_salary(connection)
elif choice == '8':
generate_payroll_report(connection)
elif choice == '9':
generate_average_salary_report(connection)
elif choice == '10':
get_employees_by_department(connection)
elif choice == '11':
view_employees_by_date_range(connection)
elif choice == '12':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
connection.close()
else:
print("Failed to connect to the database.")
# Run the Program
if __name__ == "__main__":
main()
OUTPUT
1) Adding Employee:
Web Reference
https://www.tutorialspoint.com/sql/
https://www.programiz.com/python-
programming