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("/insertrec") public class insertrec extends HttpServlet { private static final long serialVersionUID = 1L; // Database connection parameters private final String jdbcUrl = "jdbc:mysql://localhost:3306/nehal"; private final String dbUser = "root"; private final String dbPassword = "nehal@123"; 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"); // Set up the response content type and output writer response.setContentType("text/html"); PrintWriter out = response.getWriter(); 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 insert query String sql = "INSERT INTO emp (id, name) VALUES (?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, Integer.parseInt(id)); // Set user ID pstmt.setString(2, name); // Set user name // Execute insert int rowsInserted = pstmt.executeUpdate(); // Generate response to the client if (rowsInserted > 0) { out.println("<h1>Record inserted successfully for user ID: " + id + "</h1>"); } else { out.println("<h1>Failed to insert the record.</h1>"); } } catch (Exception e) { e.printStackTrace(); out.println("<h1>Error: " + e.getMessage() + "</h1>"); } finally { try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } out.close(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Redirect to doPost for GET requests doPost(request, response); } } /* <!DOCTYPE html> <html> <head> <title>Insert New User</title> </head> <body> <h2>Insert New User Information</h2> <form action="insertrec" method="post"> <label for="id">User ID:</label> <input type="text" id="id" name="id" required><br><br> <label for="name">Name:</label> <input type="text" id="name" name="name" required><br><br> <input type="submit" value="Insert"> </form> </body> </html> */
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter