In this section we will discuss how can we delete a single row or specified row.
Delete row using servlet
In this section we will discuss how can we delete a single row or specified row.
To solve this problem we will have to require a database table so, I first created a database table named 'data' and enter some records into it. Then I make a class named DeleteRow in java. This class extends the HttpServlet class further implemented the method doGet(). Inside the doGet() method uses the getWriter() method of ServletResponse interface with the reference of HttpServletResponse interface. Then establish a connection of database in java code and then deleted a specified row as in our example uses "delete from data where name = 'bipul' ".
Example :
DeleteRow.java
import java.io.IOException; import java.io.PrintWriter; import java.sql.DriverManager; import java.sql.Connection; 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 DeleteRow extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); PrintWriter pw = res.getWriter(); Connection con; PreparedStatement st; ResultSet rs; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:test"); st= con.prepareStatement("delete from data where name='bipul'"); int i = st.executeUpdate(); if(i!=0) pw.println("Deleting row..."); else if (i==0) { pw.println("<br>Row has been deleted successfully."); } } catch(SQLException sx) { pw.println(sx); } catch(ClassNotFoundException cx) { pw.println(cx); } } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>deleteRow</display-name> <servlet> <servlet-name>DeleteRow</servlet-name> <servlet-class>DeleteRow</servlet-class> </servlet> <servlet-mapping> <servlet-name>DeleteRow</servlet-name> <url-pattern>/DeleteRow</url-pattern> </servlet-mapping> </web-app>
Output :
Initially the database was
After running the example you will get the following output (when run first time).
When you will execute the example second time
The database table after deleting the specified row.
[ 0 ] Comments