Saturday, May 14, 2011

How to retrieve data from database, using servlet or a jsp?

Basics of Database Connectivity 
In java we have been provided with some classes and APIs with which we can make use of the database as we like. Database plays as very important role in the programming because we have to store the values somewhere in the back- end. So, we should know how we can manipulate the data in the database with the help of java,  instead of going to database for a manipulation. We have many database provided like Oracle, MySQL etc. We are using MySQL for developing this application. 
In this section, you will learn how to connect the MySQL database with the Java file. Firstly, we need to establish a connection between MySQL and Java files with the help of MySQL driver .  Now we will make our  account in MySQL database so that we can get connected to the database. After establishing a connection  we can access or retrieve data form MySQL database. We are going to make a program on connecting to a MySQL database, after going through this program you will be able to establish a connection on your own PC


Connection:
This is an interface in  java.sql package that specifies connection with specific database like: MySQL, Ms-Access, Oracle etc and java files. The SQL statements are executed within the context of the Connection interface.

Class.forName(String driver):
This method is static. It attempts to load the class and returns class instance and takes string type value (driver) after that matches class with given string.

DriverManager:
It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be register with this class.

getConnection(String url, String userName, String password):
This method establishes a connection to specified database url. It takes three string types of arguments like: 

        url: - Database url where stored or created your database
        userName: - User name of MySQL
        password: -Password of MySQL 

con.close():
This method is used for disconnecting the connection. It frees all the resources occupied by the database


Source Description 
Method 1: using servlets

The Java servlet example code below demonstrates how to retrieve data from table. In this program we are going to fetch the data from the database in the table from our java program using PreparedStatement.
To accomplish our goal we first have to make a class named as ServletFetchingDataFromDatabase which must extends the abstract HttpServlet class, the name of the class should be such that the other person can understand what this program is going to perform. The logic of the program will be written inside the doGet() method which takes two arguments, first is HttpServletRequest interface and the second one is the HttpServletResponse interface and this method can throw ServletException.
Inside this method call the getWriter() method of the PrintWriter class. We can retrieve the data from the database only and only if there is a connectivity between our database and the java program. To establish the connection between our database and the java program we firstly need to call the method forName() which is static in nature of the class ClassLoader. It takes one argument which tells about the database driver  we are going to use. Now use the static method getConnection() of the DriverManager class. This method takes three arguments and returns the Connection object. SQL statements are executed and  results are returned within the context of a connection. Now your connection has been established. Now use the method prepareStatement() of the Connection object which will return the PreparedStatement object and takes a query as its parameter. In this query we will write the task we want to perform. The Resultset object will be retrieved by using the executeQuery() method of the PreparedStatement object. Now the data will be retrieved by using the getString() method of the ResultSet object.

The code of the program is given below:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletFetchingDataFromDatabase extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException{
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
String connectionURL = “jdbc:mysql://localhost/zulfiqar”;
Connection connection=null;
try{
Class.forName(“org.gjt.mm.mysql.Driver”);
connection = DriverManager.getConnection(connectionURL, “root”, “admin”);
PreparedStatement pst = connection.prepareStatement(“Select * from emp_sal”);
ResultSet rs = pst.executeQuery();
while(rs.next()){
pw.println(rs.getString(1) +” ” + rs.getString(2)+”<br>”);
}
}
catch (Exception e){
pw.println(e);
}
pw.println(“hello”);
}
}
The Servlet example code shown above illustrates on how to retrieve data from table. The example code is useful to a beginner Java programmer who is searching for the example code on how to retrieve data from table. It will serve as reference when creating programs related to Java servlet.

method 2 : using XML in jsp

This is my context.xml under META-INF folder. 


<?xml version="1.0" encoding="UTF-8"?>


<Context path="/ConnectionPooling" docBase="ConnectionPooling" debug="5" reloadable="true" crossContext="true">
    <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
     maxActive="100" maxIdle="30" maxWait="10000"
     username="root" password="abhinava" driverClassName="com.mysql.jdbc.Driver"
     removeAbandoned="true" removeAbandonedTimeout="60"
     url="jdbc:mysql://localhost:3306/mysql?autoReconnect=true"/>
</Context>
pool.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<sql:query var="rs" dataSource="jdbc/TestDB">
select * from user
</sql:query>

<html>
  <head>
    <title>DB Test</title>
  </head>
  <body>

  <h2>Results</h2>
 
<c:forEach var="row" items="${rs.rows}">
    name: ${row.user}<br/>
</c:forEach>

  </body>
</html> 
 

1 comment:

  1. want code that retrieve data and image from database and display on jsp by searching id of product

    ReplyDelete