To delete in table, we have to use DELETE sql command.
Delete records from table
In this form, we will delete records in staff_register table. First make database connection and fetch records which we have to delete and display on the form.
Example of Delete records from database through JSP
deleteRecord.jsp form get records from database and populates on this form for further deletion 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`)
)
deleteRecord.jsp
HTML Code Example
<%@ page language="java" import="java.sql.*" errorPage="" %>
<%
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","userName", "password");
PreparedStatement psDeleteRecord=null;
String sqlDeleteRecord=null;
try
{
sqlDeleteRecord="Delete from staff_register where iEmpID=2";
psDeleteRecord=conn.prepareStatement(sqlDeleteRecord);
psDeleteRecord.executeUpdate();
}
catch(Exception e)
{
response.sendRedirect("deleteRecord.jsp");
//// On error it will send back to addRecord.jsp page
}
try{
if(psDeleteRecord!=null)
{
psDeleteRecord.close();
}
if(conn!=null)
{
conn.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<html>
<body>
Record is deleted successfully.
</body>
</html>
JDBC delete advance example
|