In this section we will discuss how can we add a new column into an existing table.
Add New Column Into Table using servlet
In this section we will discuss how can we add a new column into an existing table.
To solve this problem at first we are required a database table and to add a new column need to use a query so, I first created a table in the database and then make a java program named AddColumnIntoTable, to execute the query for adding a new column into 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 ADD Address varchar (100)" into the executeUpdate("") method of Statement interface.
Example :
AddColumnIntoTable.java
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 AddColumnIntoTable 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 ADD Address varchar(100)"); if(i!=0) pw.println("Column has been added successfully"); else pw.println("Column is not added"); 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>addColumn</display-name> <servlet> <servlet-name>AddColumnIntoTable</servlet-name> <servlet-class>AddColumnIntoTable</servlet-class> </servlet> <servlet-mapping> <servlet-name>AddColumnIntoTable</servlet-name> <url-pattern>/AddColumnIntoTable</url-pattern> </servlet-mapping> </web-app>
Output
The database table before adding the new column
When you will execute the above example you will get the following output
Table after adding the new table
[ 0 ] Comments