jsp update
Fri Nov 15 2024 06:16:20 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="updatejsp.jsp" method="post">
<label for="id">Employee 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 Department">
</form>
<h1>Updating Department</h1>
<%
// 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 = "UPDATE emp SET name = ? WHERE id = ?";
// Create PreparedStatement object
pstmt = conn.prepareStatement(sql);
// Set parameters
pstmt.setString(1, name); // Set department value
pstmt.setInt(2, Integer.parseInt(id)); // Set id value
// Execute update query
int rowsUpdated = pstmt.executeUpdate();
if (rowsUpdated > 0) {
out.println("<p>Employee department updated successfully!</p>");
} else {
out.println("<p>Error: Employee with ID " + id + " not found.</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