To update in table, we have to use UPDATE sql command.
Update records in table
In this form, we will update records in staff_register table. First make database connection and fetch records which we have to update and display on the form.
Example of Update record in database through JSP
updateRecord.jsp form get records from database and populates on this form for further updation according to requirement.
Database Table
CREATE TABLE staff_register (
`iEmpID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`sStaffName` varchar(60) DEFAULT NULL,
`sStaffDept` varchar(45) DEFAULT NULL,
`iStaffPhone` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`iEmpID`),
UNIQUE KEY `sStaffName` (`sStaffName`)
)
updateRecord.jsp
HTML Code Example
<%@ page language="java" import="java.sql.*" errorPage="" %>
<%
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
String jdbcURL="jdbc:mysql://localhost:3306/databaseName";
conn = DriverManager.getConnection(jdbcURL,"userName", "password");
PreparedStatement psUpdateRecord=null;
String sqlUpdateRecord=null;
int empID=5;
String staffName="yoh";
int staffPhone=45454545;
//// if this come blank and aphla number it will throw
/// parse int NumberFormatException exception, only number
try
{
sqlUpdateRecord="update staff_register set sStaffName=?, iStaffPhone=? where iEmpID=?";
psUpdateRecord=conn.prepareStatement(sqlUpdateRecord);
psUpdateRecord.setString(1,staffName);
psUpdateRecord.setInt(2,staffPhone);
psUpdateRecord.setInt(3,empID);
psUpdateRecord.executeUpdate();
}
catch(Exception e)
{
response.sendRedirect("updateRecord.jsp");
//// On error it will send back to addRecord.jsp page
}
try{
if(psUpdateRecord!=null)
{
psUpdateRecord.close();
}
if(conn!=null)
{
conn.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<html>
<body>
Data is updated successfully.
</body>
</html>
JDBC update advance example
|