This tutorial assumes you have knowledge on how the JDBC application work. Before accessing the database from a servlet, make sure you have the latest JDBC with a database.

The details on how to access the database using JDBC and an environment where you will go through our JDBC Tutorial.

Getting started with the concept, we will create a simple table and create a few files from the table as follows:

Create Table

To create the Employees table in TEST database, use the following steps:

Step 1:

Open a Command Prompt and change to the installation directory as follows:

C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>

Step 2:

Login to database as follows

C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********

Step 3:

Create the table Employee in TEST database as follows:

mysql> use TEST;
mysql> create table Employees
     id int not null,
     age int not null,
     first varchar (255),
     last varchar (255)
Query OK, 0 rows affected (0.08 sec)

Create Data Records

Finally you create few records in Employee table as follows:

mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)
mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');
Query OK, 1 row affected (0.00 sec)

Accessing a Database:

// Loading required libraries
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DatabaseAccess extends HttpServlet{
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
      // JDBC driver name and database URL
      static final String JDBC_DRIVER="com.mysql.jdbc.Driver";  
      static final String DB_URL="jdbc:mysql://localhost/TEST";

      //  Database credentials
      static final String USER = "root";
      static final String PASS = "password";

      // Set response content type
      PrintWriter out = response.getWriter();
      String title = "Database Result";
      String docType =
        "<!doctype html public \"-//w3c//dtd html 4.0 " +
         out.println(docType +
         "<html>\n" +
         "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor=\"#f0f0f0\">\n" +
         "<h1 align=\"center\">" + title + "</h1>\n");
         // Register JDBC driver

         // Open a connection
         conn = DriverManager.getConnection(DB_URL,USER,PASS);

         // Execute SQL query
         stmt = conn.createStatement();
         String sql;
         sql = "SELECT id, first, last, age FROM Employees";
         ResultSet rs = stmt.executeQuery(sql);

         // Extract data from result set
            //Retrieve by column name
            int id  = rs.getInt("id");
            int age = rs.getInt("age");
            String first = rs.getString("first");
            String last = rs.getString("last");

            //Display values
            out.println("ID: " + id + "<br>");
            out.println(", Age: " + age + "<br>");
            out.println(", First: " + first + "<br>");
            out.println(", Last: " + last + "<br>");

         // Clean-up environment
      }catch(SQLException se){
         //Handle errors for JDBC
      }catch(Exception e){
         //Handle errors for Class.forName
         //finally block used to close resources
         }catch(SQLException se2){
         }// nothing we can do
         }catch(SQLException se){
         }//end finally try
      } //end try

Here is an example which shows how to access TEST database using Servlet.

Now call this servlet using URL http://localhost:8080/DatabaseAccess which would display following response:

Database Result

ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal

Leave a reply