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 rs.next().

Example :

GetDataTable.java

import java.io.*;
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
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Connection con;
Statement stmt;
ResultSet rs;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:myServlet");
stmt = con.createStatement();
rs = stmt.executeQuery("Select * from servlet");
pw.println("Id "+ " Name" +" Address" + "<br>");
while(rs.next())
{
pw.println(rs.getInt(1)+" "+rs.getString(2) + " " + rs.getString(3) + "<br>");
}
}
catch (Exception e){
pw.println(e);
}
}
}

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>fetchdata</display-name>
<servlet>
<servlet-name>GetDataTable</servlet-name>
<servlet-class>GetDataTable</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>GetDataTable</servlet-name>
<url-pattern>/GetDataTable</url-pattern>
</servlet-mapping>
</web-app>

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