In this section we will discuss how can we delete an existing column from an existing table.
Delete an existing Column from Table using servlet
In this section we will discuss how can we delete an existing column from an existing table.
To solve this problem at first we are required a database table and to delete an existing column need to use a query so, I first created a table in the database and then make a java program named DeleteColumnFromTable, to execute the query for deleteing an existing column from the table. This class extends the HttpServlet class and it implements the doGet() method into which the references of HttpServletRequest and HttpServletResponse are created. To show the output on browser inside the doGet() method I used the getWriter() method of ServletResponse interface which is further inherited by HttpServletResponse interface. Further in the java program establish a connection with database and create a Statement then passes the SQL query " ALTER TABLE data DROP Address " into the executeUpdate("") method of Statement interface.
Example :
import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DeleteColumnFromTable extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); PrintWriter pw= res.getWriter(); Connection con; Statement ps; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:dataInsert"); ps=con.createStatement(); int i =ps.executeUpdate("ALTER TABLE data DROP Address"); pw.println("Column has been deleted successfully"); try { con.close(); ps.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>deleteColumnTable</display-name> <servlet> <servlet-name>DeleteColumnFromTable</servlet-name> <servlet-class>DeleteColumnFromTable</servlet-class> </servlet> <servlet-mapping> <servlet-name>DeleteColumnFromTable</servlet-name> <url-pattern>/DeleteColumnFromTable</url-pattern> </servlet-mapping> </web-app>
Output :
The database table before deleting the column
When you will execute the java program you will get the following output
And the table after deleting column
[ 0 ] Comments