Oh, sorry about the rs.getString(0). It is supposed to be rs.getString(1). That's not the root of the problem. (I was just trying to think of an example :P)
The overall design has a ServletContextListener and initialize a DBConnection object and put it as a context attribute. Then whenever a
jsp needs to query the database, I get the DBConnection object out from the context attribute and use the doSelect() method in DBConnection class. Here is some of the more important code previous to the call:
public class DBConnection {
private Connection connection;
private Statement statement;
private ResultSet resultSet;
public DBConnection(){
connect();
}
private boolean connect(){
boolean status = false;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}catch(ClassNotFoundException ex){
}
try{
connection = DriverManager.getConnection("jdbc:odbc:ODBC_MSACCESS_LOCAL");
connection.setAutoCommit(true);
status = true;
}catch(SQLException ex){
System.out.println(ex);
}
return status;
}
public ResultSet doSelect(
String query){
try{
statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY,ResultSet.CLOSE_CURSORS_AT_COMMIT);
statement.execute(query);
resultSet = statement.getResultSet();
}catch(SQLException ex){
System.out.println(ex);
resultSet = null;
}
return resultSet;
}
}
******************************
Report.jsp:
<%@ page import="db.*,java.sql.*" %>
<%
DBConnection db = (DBConnection)application.getAttribute("conn");
String query1 = "Select * from EXPENSE";
ResultSet rs = db.doSelect(query1);
out.print("<table>");
while(rs.next()){
out.print("<tr>");
out.print("<td>" + rs.getString("Date").split(" ")[0] + "</td>");
out.print("<td>" + rs.getString("Description") + "</td>");
out.print("<td>$" + rs.getDouble("Subtotal") + "</td>");
out.print("<td>$" + rs.getDouble("Total") + "</td>");
out.print("</tr>");
}
String query2 = "select sum(subtotal) AS SUMSUB", sum(total) AS SUMTOT from EXPENSE";
rs = db.doSelect(query2);
while(rs.next()){
out.print("<td><b>$" + rs.getDouble("SUMSUB") + "</b></td>");
out.print("<td><b>$" + rs.getDouble("SUMTOT") + "</b></td>");
}
out.print("</table>");
%>
...
So basically I am trying to print a list of expenses from the database, and add a last <tr></tr> to display the total expenses. If I remove the 2nd while loop and only do a rs.next() once, then this app will work (given there is at least one record)
Thanks for the effort in helping.