In this section we will discuss how can we create a table in java servlet.
Create table using Servlet
In this section we will discuss how can we create a table in java servlet.
To achieve the solution of this problem we should have a database package, here I will create a table in MS Access. To create a table in java servlet we will have to establish a connection between database and java program, for this I used the interfaces Connection, Statement, and DriverManager class of java.sql package in java code. Further I make class named CreateTable which extends the HttpServlet class, and overrides the method doGet() into which created a references of HttpServletRequest and HttpServletResponse. Then in the body of doGet() uses the getWriter() method of ServletResponse interface which returns a PrintWriter object that helps in write to show output. Then establish a connection with database, at first load the Driver and then make a connection. Then I used the query for creating table "CREATE TABLE table_name (field1(data_type), field2(data_type),--,fieldN(data_type))".
Example :
CreateTable.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 CreateTable 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(); st.executeUpdate("CREATE TABLE data1 (FirstName varchar(10), LastName varchar(10))"); pw.println("Table is created Successfully"); try { con.close(); st.close(); } catch(Exception e) { pw.println(e); } } catch(ClassNotFoundException cx) { pw.println(cx); } catch(SQLException sx) { pw.println(sx); } } }
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>createTable</display-name> <servlet> <servlet-name>CreateTable</servlet-name> <servlet-class>CreateTable</servlet-class> </servlet> <servlet-mapping> <servlet-name>CreateTable</servlet-name> <url-pattern>/CreateTable</url-pattern> </servlet-mapping> </web-app>
Output :
When you will execute the above example you will get the following output :
And in the database the table will be displayed as :
[ 0 ] Comments