In this section we will discuss how can we delete the table from database.
Delete Table using Servlet
In this section we will discuss how can we delete the table from database.
To delete a table from the database we should have a table in database. So I created first a table in database 'data1'. Further in java servlet program we will required to make a connection with database. After establish a connection I passed the query for deleting a table into the executeUpdate() method of Statement interface.
Example :
DeleteTableServlet.java
import java.io.IOException; import java.io.PrintWriter; import java.sql.DriverManager; import java.sql.Connection; import java.sql.Statement; 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 DeleteTableServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); PrintWriter pw = res.getWriter(); Connection con; Statement st; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:dataInsert"); st= con.createStatement(); int i =st.executeUpdate("DROP TABLE data1"); if(i!=0) pw.println("Tabel has been deleted successfully"); try { con.close(); st.close(); } catch(Exception e) { pw.println(e); } } 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>deleteTable</display-name> <servlet> <servlet-name>DeleteTableServlet</servlet-name> <servlet-class>DeleteTableServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DeleteTableServlet</servlet-name> <url-pattern>/DeleteTableServlet</url-pattern> </servlet-mapping> </web-app>
Output
Initially the tables in database were
When you will execute the above example the table 'data1' will be deleted.
[ 0 ] Comments