Delete All Rows using servlet

Delete All Rows using servlet

Posted in : Java Posted on : July 8, 2011 at 7:04 PM Comments : [ 0 ]

In this section we will discuss how can we delete the row from our database using servlet.

Delete All Rows using servlet

In this section we will discuss how can we delete the row from our database using servlet.

At first I have created a table 'data' in MS Access and inserted the records in table. In the example given below I make a class named DeleteAllRow which extends the HttpServlet class. In this class the doGet() method is also implemented into which make the HttpServletRequest and HttpServletResponse references respectively. Through the HttpServletResponse reference I call the getWriter() method of ServletResponse interface which is the super interface of HttpServletResponse interface that helps in to write on browser as output. Then establish the connection of database in java code which reads the total number of rows in table first and then it will delete the all the rows using query of "delete".

Example :

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DeleteAllRow extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
PrintWriter pw = res.getWriter();
Connection con;
PreparedStatement ps;
ResultSet rs;
try {
con = DriverManager.getConnection("jdbc:odbc:test");
ps = con.prepareStatement("select count (*) from data");
rs = ps.executeQuery();
while ( 
pw.println("Previously total number of rows (record) =<b> " + rs.getInt(1)+"</b>");
ps = con.prepareStatement("delete from data");
int del = ps.executeUpdate();
pw.println("<br>Number of rows deleted are =<b>"+del+"</b>");

catch (SQLException ex) 
catch (ClassNotFoundException cx) 


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="" xmlns:xsi="" xsi:schemaLocation="">


Output :

Initially I had the database table with record as follows :

When will you execute the above example you will get the following output :

Table after deleting the records :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics