Database connection of servlets

PHOTO EMBED

Sat Nov 16 2024 01:49:41 GMT+0000 (Coordinated Universal Time)

Saved by @login123

package test;
 
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("/updateUser")
public class jsplog extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get user input from the form
        String id = request.getParameter("id");
        String name = request.getParameter("name");
 
        // Database connection parameters
        String jdbcUrl = "jdbc:mysql://localhost:3306/nehal";
        String dbUser = "root";
        String dbPassword = "nehal@123";
 
        Connection conn = null;
        PreparedStatement pstmt = null;
 
        try {
            // Load the JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");
 
            // Establish a connection to the database
            conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);
 
            // Prepare SQL update query
            String sql = "UPDATE emp SET name = ? WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name); // Set new name
            pstmt.setInt(2, Integer.parseInt(id)); // Set user ID
 
            // Execute update
            int rowsUpdated = pstmt.executeUpdate();
 
            // Respond to the client
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            if (rowsUpdated > 0) {
                out.println("<h1>Record updated successfully for user ID: " + id + "</h1>");
            } else {
                out.println("<h1>No user found with ID: " + id + "</h1>");
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
//html
<!DOCTYPE html>
<html>
<head>
    <title>Update User</title>
</head>
<body>
    <h2>Update User Information</h2>
    <form action="updateUser" method="post">
        <label for="id">User ID:</label>
        <input type="text" id="id" name="id" required><br><br>
 
        <label for="name">New Name:</label>
        <input type="text" id="name" name="name" required><br><br>
 
        <input type="submit" value="Update">
    </form>
</body>
</html>
content_copyCOPY