jsp insert
Fri Nov 15 2024 06:07:05 GMT+0000 (Coordinated Universal Time)
Saved by @wtlab
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*, javax.sql.*" %>
<h2>Update Department for Employee</h2>
<form action="jspinsert.jsp" method="post">
<label for="id">Employee ID:</label>
<input type="text" id="id" name="id" required><br><br>
<label for="name">Employee Name:</label>
<input type="text" id="name" name="name" required><br><br>
<input type="submit" value="Insert Employee Record">
</form>
<h1>Inserting Employee Record</h1>
<%
//code snippets
// Get form parameters
String id = request.getParameter("id");
String name = request.getParameter("name");
// MySQL connection details
String dbURL = "jdbc:mysql://localhost:3306/nehal";
String dbUser = "root";
String dbPassword = "nehal@123";
Connection conn = null;
PreparedStatement pstmt = null;
try {
// Load MySQL JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish connection
conn = DriverManager.getConnection(dbURL, dbUser, dbPassword);
// SQL query to update department
String sql = "INSERT INTO emp (id,name) VALUES (?, ?)";
// Create PreparedStatement object
pstmt = conn.prepareStatement(sql);
// Set parameters
pstmt.setInt(1, Integer.parseInt(id)); // Set id value
pstmt.setString(2, name); // Set department value
// Execute update query
int rowsUpdated = pstmt.executeUpdate();
if (rowsUpdated > 0) {
out.println("<p>Employee row inserted successfully!</p>");
} else {
out.println("<p>Error: Employee row cannot be inserted.</p>");
}
} catch (Exception e) {
out.println("Error: " + e.getMessage());
} finally {
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException ex) {
out.println("Error closing resources: " + ex.getMessage());
}
}
%>



Comments