Sunday, April 19, 2009

Write a program to display the user details, with delete button for each detail

Write a program to display the user details, with delete button for each detail. The details get deleted from the database after clicking the corresponding delete button.

The files used to run the application are:
1. delete.jsp
2. Main.jsp
Solution:
delete.jsp

<html>
<head><title>Details</title></head>
<%@ page import="java.io.*, java.sql.*"%>
<body>
<center>
<H3>Details</h3>
<table border="1">
<tr><th>CusNr</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Delete</th></tr>
<%
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connection =
DriverManager.getConnection("jdbc:odbc:Details");
Statement statement = connection.createStatement();
String query = "Select * from UserDetails";
ResultSet resCar = statement.executeQuery(query);
while(res.next())
{
int cno = resCar.getInt("CusNr");
String first = res.getString("Fname");
String last = res.getString("Lname");
String email = res.getString("Email");
%>
<TR>
<TD><%= cno %></TD>
<TD><%= first %></TD>
<TD><%= last %></TD>
<TD><%= email %></TD>
<TD><A HREF='Main.jsp?cusnr=<%= cno
%>'>Delete</A></TD>
</TR>
<%
}// end while loop
}
catch (ClassNotFoundException cnfe)
{
System.err.println(cnfe);
}
catch (SQLException ex )
{
System.err.println( ex);
}
catch (Exception er)
{
er.printStackTrace();
}
%>
</table>
</center>
</body>
</html>

Main.jsp

<html>
<head><title>Details</title></head>
<%@ page import="java.io.*, java.sql.*"%>
<body>
<center>
<%
String inCusNr = request.getParameter("cusnr");
String delete_cus = "delete from UserDetails where CusNr="+inCusNr;
%>

<%
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connection =
DriverManager.getConnection("jdbc:odbc:banking");
Statement statement = connection.createStatement();
int rowsGone = statement.executeUpdate(delete_cus);
if (rowsGone==1)
{
%>
<H2>Details of User <%= inCusNr %> deleted.</H2>
<%
}
else
{
%>
<h2>Insertion failure</h2>
<%
}
}
catch (ClassNotFoundException cnfe)
{
System.err.println(cnfe);
}
catch (SQLException ex )
{
System.err.println( ex);
}
catch (Exception er)
{
er.printStackTrace();
}
%>
</center>
</body>
</html>

The output of the program is as shown in the Figure 14.6.
Figure 14.6: User Details in Database

When the user clicks on Delete button for any detail, the corresponding user detail will be deleted from the database, and a message will be displayed to the user, as shown in Figure 14.7.

Figure 14.7: Deletion Message

0 nhận xét: