Sistema de gestión de empleados usando Python

La tarea es crear un sistema de gestión de empleados basado en una base de datos en Python que almacenará la información en la base de datos MySQL. El script contendrá las siguientes operaciones:

  • Agregar empleado
  • Eliminar empleado
  • Promocionar empleado
  • Mostrar empleados

La idea es que realicemos diferentes cambios en nuestro registro de empleados usando diferentes funciones, por ejemplo, Add_Employee insertará una nueva fila en nuestro empleado, también crearemos una función de eliminación de empleados que eliminará el registro de cualquier empleado existente en particular en nuestro Mesa de empleados. Este sistema funciona con los conceptos de tomar la información de la base de datos, realizar los cambios necesarios en los datos obtenidos y aplicar los cambios en el registro que veremos en nuestro Sistema de Promoción de Empleados. También podemos tener la información sobre todos los empleados existentes usando la función Mostrar empleado. La principal ventaja de conectar nuestro programa a la base de datos es que la información se vuelve sin pérdidas incluso después de cerrar nuestro programa varias veces.

Empezando

Para crear el Sistema de gestión de empleados en Python que usa la base de datos MySQL, necesitamos conectar Python con MySQL.

Para realizar una conexión, necesitamos instalar mysqlconnector , lo que se puede hacer escribiendo el siguiente comando en el símbolo del sistema de Windows.

pip install mysqlconnector

Ahora, después de la instalación exitosa de mysqlconnector, podemos conectar MySQL con Python, lo que se puede hacer escribiendo el siguiente código 

Python3

import mysql.connector
 
 
con = mysql.connector.connect(
    host="localhost", user="root", password="password", database="emp")

Ahora hemos terminado con las conexiones, por lo que podemos centrarnos en nuestro sistema de gestión de empleados 

Tabla en uso:

Registro de empleados

La idea es que mantengamos toda la información sobre el Empleado en la tabla anterior y manipulemos la tabla cuando sea necesario. Así que ahora veremos el funcionamiento de cada operación en detalle.

Verifique la función del empleado

La función de verificación de empleado toma la identificación del empleado como parámetro y verifica si existe algún empleado con la identificación dada en el registro de detalles del empleado o no. Para verificar esto, utiliza la función cursor.rowcount() que cuenta el número de filas que coinciden con los detalles dados. Es una función de utilidad, y veremos su uso en operaciones posteriores como Agregar función de empleado, etc.

Programa:

Python3

# Function To Check if Employee with
# given Id Exist or Not
 
def check_employee(employee_id):
 
    # Query to select all Rows f
    # rom employee Table
    sql = 'select * from empd where id=%s'
 
    # making cursor buffered to make
    # rowcount method work properly
    c = con.cursor(buffered=True)
    data = (employee_id,)
 
    # Executing the SQL Query
    c.execute(sql, data)
 
    # rowcount method to find
    # number of rows with given values
    r = c.rowcount
     
    if r == 1:
        return True
    else:
        return False

Agregar función de empleado

La función Agregar empleado solicitará la identificación del empleado y utiliza la función de verificación de empleado para verificar si el empleado que se agregará ya existe en nuestro registro o no, si los detalles del empleado aún no existen, entonces solicita los detalles del empleado para agregar como Nombre del empleado, Cargo del empleado y Salario del empleado. Ahora, después de obtener todos esos detalles del usuario de ese sistema, simplemente inserta la información en nuestra tabla de detalles del empleado.

Programa:

Python3

# Function to mAdd_Employee
 
def Add_Employ():
 
    Id = input("Enter Employee Id : ")
 
    # Checking if Employee with given Id
    # Already Exist or Not
    if(check_employee(Id) == True):
        print("Employee aready exists\nTry Again\n")
        menu()
     
    else:
        Name = input("Enter Employee Name : ")
        Post = input("Enter Employee Post : ")
        Salary = input("Enter Employee Salary : ")
        data = (Id, Name, Post, Salary)
 
        # Inserting Employee details in the Employee
        # Table
        sql = 'insert into empd values(%s,%s,%s,%s)'
        c = con.cursor()
 
        # Executing the SQL Query
        c.execute(sql, data)
 
        # commit() method to make changes in the table
        con.commit()
        print("Employee Added Successfully ")
        menu()

Eliminar función de empleado

La función Eliminar empleado simplemente solicitará la identificación del empleado que se eliminará porque la identificación es la clave principal en nuestro registro de detalles del empleado, ya que puede haber dos empleados con el mismo nombre, pero deben tener una identificación única. La función Eliminar empleado utiliza la función de verificación de empleado para verificar si el empleado que se eliminará existe en nuestro registro o no, si existen detalles del empleado y luego de obtener una identificación de empleado válida, elimina el registro correspondiente a esa identificación de empleado.

Programa

Python3

# Function to Remove Employee with given Id
def Remove_Employ():
    Id = input("Enter Employee Id : ")
 
    # Checking if Employee with given Id
    # Exist or Not
    if(check_employee(Id) == False):
        print("Employee does not  exists\nTry Again\n")
        menu()
     
    else:
         
        # Query to Delete Employee from Table
        sql = 'delete from empd where id=%s'
        data = (Id,)
        c = con.cursor()
 
        # Executing the SQL Query
        c.execute(sql, data)
 
        # commit() method to make changes in
        # the table
        con.commit()
        print("Employee Removed")
        menu()

Promover la función del empleado

La función Promover empleado solicitará la identificación del empleado y utiliza la función de verificación de empleado para verificar si el empleado que se promocionará existe en nuestro registro o no, si existen detalles del empleado, entonces solicitará la cantidad en la que se aumentará su salario. Después de obtener los detalles válidos, aumenta el salario del empleado con la identificación dada por la cantidad dada.

Programa

Python3

# Function to Promote Employee
def Promote_Employee():
    Id = int(input("Enter Employ's Id"))
 
    # Checking if Employee with given Id
    # Exist or Not
    if(check_employee(Id) == False):
        print("Employee does not  exists\nTry Again\n")
        menu()
    else:
        Amount = int(input("Enter increase in Salary"))
 
        # Query to Fetch Salary of Employee with
        # given Id
        sql = 'select salary from empd where id=%s'
        data = (Id,)
        c = con.cursor()
 
        # Executing the SQL Query
        c.execute(sql, data)
 
        # Fetching Salary of Employee with given Id
        r = c.fetchone()
        t = r[0]+Amount
 
        # Query to Update Salary of Employee with
        # given Id
        sql = 'update empd set salary=%s where id=%s'
        d = (t, Id)
 
        # Executing the SQL Query
        c.execute(sql, d)
 
        # commit() method to make changes in the table
        con.commit()
        print("Employee Promoted")
        menu()

Mostrar función de empleados

La función Mostrar empleados es simplemente una consulta de selección de SQL que obtiene todos los registros almacenados en la tabla de detalles de los empleados y los imprime línea por línea.

Programa:

Python3

# Function to Display All Employees
# from Employee Table
 
def Display_Employees():
     
    # query to select all rows from
    # Employee Table
    sql = 'select * from empd'
    c = con.cursor()
     
    # Executing the SQL Query
    c.execute(sql)
     
    # Fetching all details of all the
    # Employees
    r = c.fetchall()
    for i in r:
        print("Employee Id : ", i[0])
        print("Employee Name : ", i[1])
        print("Employee Post : ", i[2])
        print("Employee Salary : ", i[3])
        print("-----------------------------\
        -------------------------------------\
        -----------------------------------")
    menu()

Función del menú

La función Menú muestra el menú al usuario y le pide que ingrese su elección para realizar operaciones como Agregar empleado, Eliminar empleado, etc.

Programa

Python3

# menu function to display the menu
def menu():
    print("Welcome to Employee Management Record")
    print("Press ")
    print("1 to Add Employee")
    print("2 to Remove Employee ")
    print("3 to Promote Employee")
    print("4 to Display Employees")
    print("5 to Exit")
     
    # Taking choice from user
    ch = int(input("Enter your Choice "))
    if ch == 1:
        Add_Employ()
         
    elif ch == 2:
        Remove_Employ()
         
    elif ch == 3:
        Promote_Employee()
         
    elif ch == 4:
        Display_Employees()
         
    elif ch == 5:
        exit(0)
         
    else:
        print("Invalid Choice")
        menu()

Código completo:

Python3

# importing mysql connector
import mysql.connector
 
# making Connection
con = mysql.connector.connect(
    host="localhost", user="root", password="password", database="emp")
 
# Function to mAdd_Employee
def Add_Employ():
 
    Id = input("Enter Employee Id : ")
     
    # Checking if Employee with given Id
    # Already Exist or Not
    if(check_employee(Id) == True):
        print("Employee aready exists\nTry Again\n")
        menu()
         
    else:
        Name = input("Enter Employee Name : ")
        Post = input("Enter Employee Post : ")
        Salary = input("Enter Employee Salary : ")
        data = (Id, Name, Post, Salary)
     
        # Inserting Employee details in
        # the Employee Table
        sql = 'insert into empd values(%s,%s,%s,%s)'
        c = con.cursor()
         
        # Executing the SQL Query
        c.execute(sql, data)
         
        # commit() method to make changes in
        # the table
        con.commit()
        print("Employee Added Successfully ")
        menu()
 
# Function to Promote Employee
def Promote_Employee():
    Id = int(input("Enter Employ's Id"))
     
    # Checking if Employee with given Id
    # Exist or Not
    if(check_employee(Id) == False):
        print("Employee does not  exists\nTry Again\n")
        menu()
    else:
        Amount = int(input("Enter increase in Salary"))
         
        # Query to Fetch Salary of Employee
        # with given Id
        sql = 'select salary from empd where id=%s'
        data = (Id,)
        c = con.cursor()
         
        # Executing the SQL Query
        c.execute(sql, data)
         
        # Fetching Salary of Employee with given Id
        r = c.fetchone()
        t = r[0]+Amount
         
        # Query to Update Salary of Employee with
        # given Id
        sql = 'update empd set salary=%s where id=%s'
        d = (t, Id)
         
        # Executing the SQL Query
        c.execute(sql, d)
         
        # commit() method to make changes in the table
        con.commit()
        print("Employee Promoted")
        menu()
 
# Function to Remove Employee with given Id
def Remove_Employ():
    Id = input("Enter Employee Id : ")
     
    # Checking if Employee with given Id Exist
    # or Not
    if(check_employee(Id) == False):
        print("Employee does not  exists\nTry Again\n")
        menu()
    else:
         
        # Query to Delete Employee from Table
        sql = 'delete from empd where id=%s'
        data = (Id,)
        c = con.cursor()
         
        # Executing the SQL Query
        c.execute(sql, data)
         
        # commit() method to make changes in
        # the table
        con.commit()
        print("Employee Removed")
        menu()
 
 
# Function To Check if Employee with
# given Id Exist or Not
def check_employee(employee_id):
     
    # Query to select all Rows f
    # rom employee Table
    sql = 'select * from empd where id=%s'
     
    # making cursor buffered to make
    # rowcount method work properly
    c = con.cursor(buffered=True)
    data = (employee_id,)
     
    # Executing the SQL Query
    c.execute(sql, data)
     
    # rowcount method to find
    # number of rows with given values
    r = c.rowcount
    if r == 1:
        return True
    else:
        return False
 
# Function to Display All Employees
# from Employee Table
def Display_Employees():
     
    # query to select all rows from
    # Employee Table
    sql = 'select * from empd'
    c = con.cursor()
     
    # Executing the SQL Query
    c.execute(sql)
     
    # Fetching all details of all the
    # Employees
    r = c.fetchall()
    for i in r:
        print("Employee Id : ", i[0])
        print("Employee Name : ", i[1])
        print("Employee Post : ", i[2])
        print("Employee Salary : ", i[3])
        print("---------------------\
        -----------------------------\
        ------------------------------\
        ---------------------")
         
    menu()
 
# menu function to display menu
def menu():
    print("Welcome to Employee Management Record")
    print("Press ")
    print("1 to Add Employee")
    print("2 to Remove Employee ")
    print("3 to Promote Employee")
    print("4 to Display Employees")
    print("5 to Exit")
 
    ch = int(input("Enter your Choice "))
    if ch == 1:
        Add_Employ()
    elif ch == 2:
        Remove_Employ()
    elif ch == 3:
        Promote_Employee()
    elif ch == 4:
        Display_Employees()
    elif ch == 5:
        exit(0)
    else:
        print("Invalid Choice")
        menu()
 
 
# Calling menu function
menu()

Producción

Publicación traducida automáticamente

Artículo escrito por srivastavaharshit848 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *