Updating Database Records

PHOTO EMBED

Sun Nov 03 2024 18:12:03 GMT+0000 (Coordinated Universal Time)

Saved by @login123

Servlet Code for Updating Database Records
The servlet will receive id, name, and age parameters from the client, which it will use to update the name and age fields of a specific user in the database.

java
Copy code
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/UpdateUserServlet")
public class UpdateUserServlet extends HttpServlet {

    private static final String DB_URL = "jdbc:mysql://localhost:3306/yourDatabaseName";
    private static final String DB_USER = "yourUsername";
    private static final String DB_PASSWORD = "yourPassword";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Get parameters from the request
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String age = request.getParameter("age");

        // Set response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            // Load JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish database connection
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);

            // Prepare the SQL update statement
            String sql = "UPDATE users SET name = ?, age = ? WHERE id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, name);
            stmt.setInt(2, Integer.parseInt(age));
            stmt.setInt(3, Integer.parseInt(id));

            // Execute update and check if a record was updated
            int rowsUpdated = stmt.executeUpdate();
            if (rowsUpdated > 0) {
                out.println("<h1>User updated successfully!</h1>");
            } else {
                out.println("<h1>User not found or update failed.</h1>");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            out.println("<h1>Error: Unable to load database driver.</h1>");
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("<h1>Error: Unable to execute update operation.</h1>");
        } finally {
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
content_copyCOPY