Monday, 20 July 2015

How To Use Multiple Resultset in JAVA / JSP

              In this post, I have given sample program for using multiple ResultSet objects in the same Java program.
              Here I have written code in JSP. Database used is Mysql. Mysql database name is "test". Database User name is "test" while password is "123".
              In same Java program, when we have to use two ResultSet objects, we have to use two Statement objects with only one Connection object. It is shown in following program followed by output webpage.
              Here, I am retrieving records from two tables, "firsttable" and "secondtable". Their configuration is shown in following tables:


Configuration of Table: firsttable


Configuration of Table: secondtable

Program:
<%@ page import="java.sql.*" %>
<html>

<head>
</head>

<body>

<div style="background-color:SlateGray">
<h1>Web Application for Multiple ResultSet</h1>
</div>

<br>
<br>

<%
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "test";
String driver = "com.mysql.jdbc.Driver";
String userName ="test";
String password="123";

Statement st1,st2;
ResultSet rs1,rs2;
String query1,query2;

try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db,userName,password);

query1 = "select * from firsttable;";

query2="select * from secondtable;";

st1 = con.createStatement();
st2=con.createStatement();

rs1 = st1.executeQuery(query1);
rs2 = st2.executeQuery(query2);
%>

<b>Contents of Table: firsttable</b>
<br />
<br />

<table border="1">
<tr><th>Unit No.</th><th>Topic</th><th>Description</th><th>Hours Required</th></tr>
<%
while(rs1.next()){
%>
<tr><td><%=rs1.getString(1)%></td>
<td><%=rs1.getString(2)%></td>
<td><%=rs1.getString(3)%></td>
<td><%=rs1.getString(4)%></td>
</tr>
<%
}
%>

</table>

<br />
<br />
<br />

<b>Contents of Table: secondtable</b>
<br />
<br />

<table border="1">
<tr><th>Date</th><th>Unit No.</th><th>Topic</th><th>Description</th></tr>

<%

while(rs2.next()){
%>
<tr><td><%=rs2.getString(1)%></td>
<td><%=rs2.getString(2)%></td>
<td><%=rs2.getString(3)%></td>
<td><%=rs2.getString(4)%></td>
</tr>
<%
}

%>

<%
}
catch(Exception e){
e.printStackTrace();
}
%>
</table>

<br />
<br />

<div style="background-color:SlateGray">
Sample JDBC-JSP program for Multiple ResultSet in Same Program
</div>

</body>
</html>

No comments:

Post a Comment