Database Access in Servlets


  • To access the database in Servlet, load the JDBC driver and return the Connection object.
  • The Connection object is used to create Statement object. Before starting with database access through servlet, make sure that the proper JDBC connection with database has been setup.

Accessing a Database

Following files are required for accessing the database:
i. welcome.html
iii. web.xml
iv. ojdbc14.jar

Note: We are using Oracle database and type 4 (thin driver) to connect with Servlet application.

Example : Accessing the database and displaying the record


<form action="show" method="post">
      Enter Table Name : <input type="text" name="table">
      <input type="submit" value="Show Records">


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
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 ServletDatabaseDemo extends HttpServlet  
      protected void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException,IOException
           PrintWriter pw = res.getWriter();
           String tableName = req.getParameter("table");
               Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott","tiger");
               Statement st=con.createStatement();
               System.out.println ("connection established successfully...!!");     
               ResultSet rs = st.executeQuery("Select * from "+tableName);
               pw.println("<table border=1>");
           catch (Exception e)