Edit Employee

Hello readers how are you doing? In the last article, I have started a simple Java Servlet project on Employee Management System. This is the 3rd  part of the Employee Management System. In this article, I’m going to explain how you can update data to the database and show updated data in an HTML file.

To update data we are fetching data from the database and showing that into the main HTML file from there only you can edit data and save data to the database. Previously I’ve written the front-end code for updating but not included Backend code. I used the font awesome icon to show the edit button and delete button.

 What is CRUD:

In a database we mainly perform Create, Read, Update and Delete operations. Their operations are basically called CRUD operations in short.

  • CreateThis operation is used to insert data into the database.
  • Read – is Used to fetch the data from Database.
  • Update – This Operation is used to update data on the database or make changes to the existing Data.
  • Delete – Last operation is Delete, is used to delete data prom database.

Each of the operations has its own query to perform their respective tasks.

The syntax for Updating data to Database:

Generally, an Update keyword is used to perform update operations to the database. And we can also use where a condition for some specific update.

Database Structure Geeksteps

Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Example:

update geeksteps.employee set name=?,email=?,contact=?,password=? where id=1;

I hope you understand the concept of Updating data to Database. You have the project ready and you understood the concept of updating data then let’s create the Servlet class.

Add Methods in EmployeeMain.java

In the previous article, we created a controller class which contains all the MySQL DB connection related codes. Now open the EmployeeMain.java file and paste the below code before closing the final brackets.

public static Employee getEmployeeById(int id) {
Employee emp=new Employee();  

try{  
            Connection con=EmployeeMain.getConnection();  
            PreparedStatement ps=con.prepareStatement("select * from geeksteps.employee where id=?");  
            ps.setInt(1,id);  
            ResultSet rs=ps.executeQuery();  
            if(rs.next()){  
                emp.setId(rs.getInt(1));  
                emp.setName(rs.getString(2));  
                emp.setEmail(rs.getString(3));  
                emp.setContact(rs.getString(4));  
                emp.setContact(rs.getString(5));  
            }  
            con.close();  
        }catch(Exception ex){ex.printStackTrace();}  
          
return emp;
}  

public static int updateEmployee(Employee e){  
        int status=0;  
        try{  
            Connection con=EmployeeMain.getConnection();  
            PreparedStatement ps=con.prepareStatement(  
                         "update geeksteps.employee set name=?,email=?,contact=?,password=? where id=?");  
            ps.setString(1,e.getName());  
            ps.setString(2,e.getEmail());  
            ps.setString(3,e.getContact());  
            ps.setString(4,e.getPassword());  
            ps.setInt(5,e.getId());  
              
            status=ps.executeUpdate();  
              
            con.close();  
        }catch(Exception ex){ex.printStackTrace();}  
          
        return status;  
    }  

Here I’m adding two methods,
1. getEmployeeById() which takes an integer as input which takes id as input whose data will be updated. This method fetches the data from the database and shows that data into the HTML file, show that the data can be updated.
2. The second method is updateEmployee() which takes the Employee object as an argument. This method is also responsible for updating the data into the database and save.

Creating Servlet:

Create a servlet class inside your package and save the file as UpdateEmployeeServlet.java. This file contains the code which takes the change data from the HTML file and saves the new data into the database. After saving the data it redirects the page to viewEmployeeServlet page so that all data along with updated data. Copy the following code and paste the code into the UpdateEmployeeServlet file.

package com.geeksteps.employee;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
 
/**
 * Servlet implementation class UpdateEmployeeServlet
 */
@WebServlet("/UpdateEmployeeServlet")
public class UpdateEmployeeServlet extends GenericServlet {
 private static final long serialVersionUID = 1L;
 
 public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
 
   PrintWriter printWriter=response.getWriter();  
 String eid=request.getParameter("id");  
        int id=Integer.parseInt(eid);  
        String name=request.getParameter("name");  
        String email=request.getParameter("email");  
        String contact=request.getParameter("contact");  
        String password=request.getParameter("password"); 

        Employee e=new Employee();  
        e.setId(id);  
        e.setName(name);  
        e.setEmail(email);  
        e.setContact(contact);  
        e.setPassword(password);  
        
        
        int status=EmployeeMain.updateEmployee(e);  
        if(status>0){  
         printWriter.print("<script>window.alert('Record Updated Successfully')</script>");  
         request.getRequestDispatcher("ViewEmployeesServlet").include(request, response); 
        }else{  
         
            printWriter.println("Sorry! unable to update record");  
        }  
 }
 
}
 

After running the project when you will click on the view Employees button it will display a table with a list of the employees along with their all details. Besides the details, you can see the edit and delete button also implemented. When you will edit any employee details then it will open all the details in the same form in which you added all details.

Conclusion

So I hope you have understood how you can update data into the database using Java and Servlet. If you have any problem ask me in the comment section. The source code is provided below.
If you found this article helpful then don’t be cheap to share. See you at the next one.
Subscribe to GeekSteps

Happy Coding 😉

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here