Code for Employee Management System

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Code for Employee Management System

First, make sure you've installed mysql-connector-python:

pip install mysql-connector-python

Then, run the code below to create the Employee Management System.

import mysql.connector

# Connect to MySQL Database

db = mysql.connector.connect(

host="localhost",

user="yourusername",

password="yourpassword",

database="employee_db"

cursor = db.cursor()

# Create Database and Table (only needed once)

cursor.execute("CREATE DATABASE IF NOT EXISTS employee_db")

cursor.execute("USE employee_db")

cursor.execute("""

CREATE TABLE IF NOT EXISTS employees (

id INT AUTO_INCREMENT PRIMARY KEY,


name VARCHAR(255),

age INT,

department VARCHAR(255),

salary FLOAT

""")

# Function to Add an Employee

def add_employee(name, age, department, salary):

query = "INSERT INTO employees (name, age, department, salary)


VALUES (%s, %s, %s, %s)"

values = (name, age, department, salary)

cursor.execute(query, values)

db.commit()

print(f"Employee {name} added successfully.")

# Function to Display All Employees

def display_employees():

cursor.execute("SELECT * FROM employees")

employees = cursor.fetchall()

print("ID\tName\t\tAge\tDepartment\tSalary")

print("-" * 50)

for emp in employees:


print(f"{emp[0]}\t{emp[1]}\t\t{emp[2]}\t{emp[3]}\t\t{emp[4]}")

# Function to Update Employee Information

def update_employee(emp_id, name=None, age=None, department=None,


salary=None):

query = "UPDATE employees SET "

values = []

if name:

query += "name = %s, "

values.append(name)

if age:

query += "age = %s, "

values.append(age)

if department:

query += "department = %s, "

values.append(department)

if salary:

query += "salary = %s, "

values.append(salary)

query = query.rstrip(", ")

query += " WHERE id = %s"

values.append(emp_id)
cursor.execute(query, tuple(values))

db.commit()

print(f"Employee ID {emp_id} updated successfully.")

# Function to Delete an Employee

def delete_employee(emp_id):

query = "DELETE FROM employees WHERE id = %s"

cursor.execute(query, (emp_id,))

db.commit()

print(f"Employee ID {emp_id} deleted successfully.")

# Example Usage

add_employee("Alice", 30, "HR", 50000)

add_employee("Bob", 25, "Engineering", 70000)

add_employee("Charlie", 28, "Sales", 60000)

display_employees()

update_employee(2, age=26, department="Marketing")

delete_employee(3)

display_employees()

# Close the cursor and connection


cursor.close()

db.close()

—---------------------------------------------------------------------

Examples

You might also like