Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
How to make a Python auto clicker?
Next article icon

The task is to create a Database-driven Employee Management System in Python that will store the information in the MySQL Database. The script will contain the following operations :

The idea is that we perform different changes in our Employee Record by using different functions for example the Add_Employee will insert a new row in our Employee, also, we will create a Remove Employee Function which will delete the record of any particular existing employee in our Employee table. This System works on the concepts of taking the information from the database making required changes in the fetched data and applying the changes in the record which we will see in our Promote Employee System. We can also have information about all the existing employees by using the Display Employee function. The main advantage of connecting our program to the database is that the information becomes lossless even after closing our program a number of times.

Getting Started

For creating the Employee Management System in Python that uses MySQL database we need to connect Python with MySQL.

For making a connection we need to installmysqlconnector which can be done by writing the following command in the command prompt on Windows.

pip install mysql-connector-python

Now after the successful installation of the MySQL connector, we can connect MySQL with Python which can be done by writing the following code 

Python
importmysql.connectorcon=mysql.connector.connect(host="localhost",user="root",password="password",database="emp")

Now we are Done with the connections, so we can focus on our Employee Management System 

Table in Use:

Employee Record

The idea is that we keep all the information about theEmployee in the above table and manipulate the table whenever required. So now we will look at the working of each operation in detail.

Check Employee Function

The check employee function takes employee id as a parameter and checks whether any employee with given id exists in the employee details record or not. For checking this it usescursor.rowcount() function which counts the number of rows that match with given details. It is a utility function, and we will see its use in later operations like Add employee function, etc.,

Python
defcheck_employee(employee_id):# Query to select all rows from the employees table where id matchessql='SELECT * FROM employees WHERE id=%s'# Making cursor buffered to make rowcount method work properlycursor=con.cursor(buffered=True)data=(employee_id,)# Executing the SQL Querycursor.execute(sql,data)# Fetch the first row to check if employee existsemployee=cursor.fetchone()# Closing the cursorcursor.close()# If employee is found, return True, else return FalsereturnemployeeisnotNone

Add Employee Function

The Add Employee function will ask for the Employee Id and uses the check employee function to check whether the employee to be added already exist in our record or not if employee details do not already exist then it asks for details of the employee to be added like Employee Name, Post of Employee and Salary of the employee. Now after getting all such details from the user of that system it simply inserts the information in our Employee details table.

Python
defadd_employee():Id=input("Enter Employee Id: ")# Checking if Employee with given Id already existsifcheck_employee(Id):print("Employee already exists. Please try again.")returnelse:Name=input("Enter Employee Name: ")Post=input("Enter Employee Post: ")Salary=input("Enter Employee Salary: ")# Inserting Employee details into the employees tablesql='INSERT INTO employees (id, name, position, salary) VALUES (%s,%s,%s,%s)'data=(Id,Name,Post,Salary)cursor=con.cursor()try:# Executing the SQL Querycursor.execute(sql,data)# Committing the transactioncon.commit()print("Employee Added Successfully")exceptmysql.connector.Erroraserr:print(f"Error:{err}")con.rollback()finally:# Closing the cursorcursor.close()

Remove Employee Function

The Remove Employee Function will simply ask for Id of the employee to be removed because Id isPrimary key in our Employee Details Record as there can be two employees with the same name, but they must have a unique id. The Remove Employee function uses the check employee function to check whether the employee to be removed exists in our record or not if employee details exist then after getting a valid employee id it deletes the record corresponding to that employee id.

Python
defremove_employee():Id=input("Enter Employee Id: ")# Checking if Employee with given Id existsifnotcheck_employee(Id):print("Employee does not exist. Please try again.")returnelse:# Query to delete employee from the employees tablesql='DELETE FROM employees WHERE id=%s'data=(Id,)cursor=con.cursor()try:# Executing the SQL Querycursor.execute(sql,data)# Committing the transactioncon.commit()print("Employee Removed Successfully")exceptmysql.connector.Erroraserr:print(f"Error:{err}")con.rollback()finally:# Closing the cursorcursor.close()

Promote Employee Function

The Promote Employee function will ask for the Employee Id and uses the check employee function to check whether the employee to be Promoted exist in our record or not if employee details exist then it will ask for the amount by which his salary is to be increased. After getting the valid details it increases the salary of the employee with the given id by the given amount.

Python
defpromote_employee():Id=input("Enter Employee's Id: ")# Checking if Employee with given Id existsifnotcheck_employee(Id):print("Employee does not exist. Please try again.")returnelse:try:Amount=float(input("Enter increase in Salary: "))# Query to Fetch Salary of Employee with given Idsql_select='SELECT salary FROM employees WHERE id=%s'data=(Id,)cursor=con.cursor()# Executing the SQL Querycursor.execute(sql_select,data)# Fetching Salary of Employee with given Idcurrent_salary=cursor.fetchone()[0]new_salary=current_salary+Amount# Query to Update Salary of Employee with given Idsql_update='UPDATE employees SET salary=%s WHERE id=%s'data_update=(new_salary,Id)# Executing the SQL Query to update salarycursor.execute(sql_update,data_update)# Committing the transactioncon.commit()print("Employee Promoted Successfully")except(ValueError,mysql.connector.Error)ase:print(f"Error:{e}")con.rollback()finally:# Closing the cursorcursor.close()

Display Employees Function

The Display Employees function is simply a select query of SQL which fetches all the records stored in the employee details table and prints them line by line.

Python
defdisplay_employees():try:# Query to select all rows from the employees tablesql='SELECT * FROM employees'cursor=con.cursor()# Executing the SQL Querycursor.execute(sql)# Fetching all details of all the Employeesemployees=cursor.fetchall()foremployeeinemployees:print("Employee Id : ",employee[0])print("Employee Name : ",employee[1])print("Employee Post : ",employee[2])print("Employee Salary : ",employee[3])print("------------------------------------")exceptmysql.connector.Erroraserr:print(f"Error:{err}")finally:# Closing the cursorcursor.close()

Menu Function

The Menu function displays the menu to the user and asks the user to enter his choice for performing operations like Add employee, Remove employee, etc.

Python
defmenu():whileTrue:print("\nWelcome 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 userch=input("Enter your Choice: ")ifch=='1':add_employee()elifch=='2':remove_employee()elifch=='3':promote_employee()elifch=='4':display_employees()elifch=='5':print("Exiting the program. Goodbye!")breakelse:print("Invalid Choice! Please try again.")

Complete Code:

Python
importmysql.connector# Database connectioncon=mysql.connector.connect(host="localhost",user="root",password="password",database="emp")cursor=con.cursor()# Function to check if an employee existsdefcheck_employee(employee_id):sql='SELECT * FROM employees WHERE id=%s'cursor.execute(sql,(employee_id,))returncursor.rowcount==1# Function to add an employeedefadd_employee():Id=input("Enter Employee Id: ")ifcheck_employee(Id):print("Employee already exists. Please try again.")returnName=input("Enter Employee Name: ")Post=input("Enter Employee Post: ")Salary=input("Enter Employee Salary: ")sql='INSERT INTO employees (id, name, position, salary) VALUES (%s,%s,%s,%s)'data=(Id,Name,Post,Salary)try:cursor.execute(sql,data)con.commit()print("Employee Added Successfully")exceptmysql.connector.Erroraserr:print(f"Error:{err}")con.rollback()# Function to remove an employeedefremove_employee():Id=input("Enter Employee Id: ")ifnotcheck_employee(Id):print("Employee does not exist. Please try again.")returnsql='DELETE FROM employees WHERE id=%s'data=(Id,)try:cursor.execute(sql,data)con.commit()print("Employee Removed Successfully")exceptmysql.connector.Erroraserr:print(f"Error:{err}")con.rollback()# Function to promote an employeedefpromote_employee():Id=input("Enter Employee's Id: ")ifnotcheck_employee(Id):print("Employee does not exist. Please try again.")returntry:Amount=float(input("Enter increase in Salary: "))sql_select='SELECT salary FROM employees WHERE id=%s'cursor.execute(sql_select,(Id,))current_salary=cursor.fetchone()[0]new_salary=current_salary+Amountsql_update='UPDATE employees SET salary=%s WHERE id=%s'cursor.execute(sql_update,(new_salary,Id))con.commit()print("Employee Promoted Successfully")except(ValueError,mysql.connector.Error)ase:print(f"Error:{e}")con.rollback()# Function to display all employeesdefdisplay_employees():try:sql='SELECT * FROM employees'cursor.execute(sql)employees=cursor.fetchall()foremployeeinemployees:print("Employee Id : ",employee[0])print("Employee Name : ",employee[1])print("Employee Post : ",employee[2])print("Employee Salary : ",employee[3])print("------------------------------------")exceptmysql.connector.Erroraserr:print(f"Error:{err}")# Function to display the menudefmenu():whileTrue:print("\nWelcome 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=input("Enter your Choice: ")ifch=='1':add_employee()elifch=='2':remove_employee()elifch=='3':promote_employee()elifch=='4':display_employees()elifch=='5':print("Exiting the program. Goodbye!")breakelse:print("Invalid Choice! Please try again.")if__name__=="__main__":menu()

Output


Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp