Get data from database in servlet

Get data from database in servlet

Posted in : Java Posted on : July 7, 2011 at 7:15 PM Comments : [ 0 ]

In this section we will discuss how can we get data from the database in servlet.

Get data from database in servlet

In this section we will discuss how can we get data from the database in servlet.

In the example given below to accomplish this problem at first I create a database myServlet and the table servlet and also created DSN, then I make a class named GetDataTable in java servlet. In this class I make the objects of the Classes Connection, Statement, ResultSet, and for display the output on screen I created an object of PrintWriter class. In the example the executed query will be stored in ResultSet object and then we will display the table's data with the help of getString() method of ResultSet object by iterating

Example :

import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class GetDataTable extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
PrintWriter pw = res.getWriter();
Connection con;
Statement stmt;
ResultSet rs;
con = DriverManager.getConnection("jdbc:odbc:myServlet");
stmt = con.createStatement();
rs = stmt.executeQuery("Select * from servlet");
pw.println("Id "+ " Name" +" Address" + "<br>");
pw.println(rs.getInt(1)+" "+rs.getString(2) + " " + rs.getString(3) + "<br>");
catch (Exception e){


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="" xmlns:xsi="" xsi:schemaLocation="">


Output :

When you will execute the above example you will get the following output :

And we had the data into database :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics