查询数据库后是返回ResultSet实现中遇到的问题

02-10-11 蓝色虾

看了板桥先生的《查询数据库...》这篇文章后觉得Iterator处理方式觉得十分不错,有意拿来尝试,可是在事件过程中遇到了困难,难以解决,希望大家给与帮助。先附上所有代码。

环境:Struts1.02+tomcat4.1+mysql

class:News(和数据库中的news表对应)

----------------------------------------

package cn.edu.njut.jp.soso.model;
import com.mysql.jdbc.ResultSet;
import java.sql.SQLException;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.Serializable;
public class News implements Serializable{
  private String newsID;
  private String subject;
  private String url;
  private String creationDate;
  private String sort;
  private String fromSite;

  public void setNewsID(String id){
    this.newsID=id;
  }
  public String getNewsID(){
    return newsID;
  }

  public void setSubject(String subject){
    this.subject=subject;
    //测试代码
    System.out.println("新闻标题为:"+subject);
  }
  public String getSubject(){
    return subject;
  }

  public void setUrl(String url){
    url=this.url;
  }
  public String getUrl(){
    return url;
  }

  public void setCreationDate(String date){
    this.creationDate=date;
  }
  public String getCreationDate(){
    return creationDate;
  }

  public void setSort(String sort){
    this.sort=sort;
  }
  public String  getSort(){
    return sort;
  }

  public void setFromSite(String site){
    this.fromSite=site;
  }
  public String getFromSite(){
    return fromSite;
  }
}

//---------------------------------------

//-DisplayAllNewsAction

//---------------------------------------

package cn.edu.njut.jp.soso.controller;

import cn.edu.njut.jp.soso.model.DisplayAllNews;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Locale;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.util.MessageResources;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;

import com.mysql.jdbc.ResultSet;

public class DisplayAllNewsAction extends Action {
  Connection connection;

  ResultSet chinaNewsResult;
  ResultSet intelNewsResult;
  ResultSet sportNewsResult;

  /**
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws IOException
   * @throws ServletException
   */
  public ActionForward perform(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
      throws IOException, ServletException{
    ActionErrors errors = new ActionErrors();
    try {
      DataSource dataSource =servlet.findDataSource(null);
      connection =dataSource.getConnection();
      //测试代码
      System.out.println("程序开始!");
      DisplayAllNews displaywelcome=new DisplayAllNews();
      displaywelcome.setConn(connection);
      chinaNewsResult=displaywelcome.getChinaNewsResult();
      intelNewsResult=displaywelcome.getIntelNewsResult();
      sportNewsResult=displaywelcome.getSportNewsResult();

      if (chinaNewsResult == null) {
        saveErrors(request, errors);
        return (new ActionForward("No chinaNewsResult in cn.edu.njut.jp.soso.controller.DisplayAllNewsAction"));
      }
      if (intelNewsResult == null) {
        saveErrors(request, errors);
        return (new ActionForward("No intelNewsResult in cn.edu.njut.jp.soso.controller.DisplayAllNewsAction"));
      }
      if (sportNewsResult == null) {
        saveErrors(request, errors);
        return (new ActionForward("No sportNewsResult in cn.edu.njut.jp.soso.controller.DisplayAllNewsAction"));
      }
      request.setAttribute("chinaNewsResult",chinaNewsResult);
      request.setAttribute("intelNewsResult",intelNewsResult);
      request.setAttribute("sportNewsResult",sportNewsResult);

      //do what you wish with myConnection
    } catch (SQLException sqle) {
      getServlet().log("Connection.process", sqle);
    } finally {
      //enclose this in a finally block to make
      //sure the connection is closed
      if(connection!=null)
        try {
        connection.close();
      } catch (SQLException e) {
        getServlet().log("Connection.close", e);
      }
    }
    return (mapping.findForward("success"));
  }
}

//--------------------------------

//--DisplayAllNews

//--------------------------------

package cn.edu.njut.jp.soso.model;

import java.sql.Connection;
import com.mysql.jdbc.ResultSet;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.SQLException;

public class DisplayAllNews {

    Connection conn;
    public void setConn(Connection conn){
      this.conn=conn;
    }

    /**
     * 取得按照加入顺序(依靠ID号)倒排的前十条数据
     * @param conn
     * @return
     * @throws SQLException
     */
    public  ResultSet getChinaNewsResult() throws SQLException{

      if(conn==null)
        throw new SQLException("No Connection in getChinaNewsResult()");

      PreparedStatement pstmt = null;
      ResultSet rs = null;
      try {
        // Prepare the query SQL
        pstmt = conn.prepareStatement("select * from news where sort='china' order by creationDate desc");
        rs = (com.mysql.jdbc.ResultSet)pstmt.executeQuery();
        //测试代码
        System.out.println("数据库中有无数据1:"+rs.next());
      }
      finally {
       // if (rs != null)//只有将这些注销后下面的println才为true
        //  rs.close();//这边一旦close。底下的rs就不能用了
       // if (pstmt != null)//这和板桥先生所说不符合,忘指教
       //   pstmt.close();//
      }
      //测试代码
      System.out.println("数据库中有无数据2:"+rs.next());
      return rs;
    }
  }

//--------------------------

//--MyIterator

//--------------------------

package cn.edu.njut.jp.soso.model;

import com.mysql.jdbc.ResultSet;
import java.util.Iterator;
import java.util.NoSuchElementException;

public abstract class MyIterator {
  protected abstract Object resultToObject(ResultSet result) throws Exception;

  public Iterator resultToIterator(ResultSet result) {
   return new ResultSetIterator(result);
 }

 protected class ResultSetIterator implements Iterator {

   private ResultSet resultSet;
   private Object next;

   public ResultSetIterator(ResultSet result) {
     this.resultSet = result;
     //测试代码
     System.out.println("在ResultSetIterator(ResultSet result)中!");
   }

   public boolean hasNext() {
     //测试代码
     System.out.println("在hasNext()中!");
     try {
       if (next == null) {
         if (!resultSet.next()) {
           //测试代码
           System.out.println("返回false!");
           return false;
         }
         next = resultToObject(resultSet);
       }
       //测试代码
       System.out.println("返回true!");
       return true;
     } catch (Exception e) {
       return false;
     }
   }

   public Object next() {
     if (!hasNext()) {
       throw new NoSuchElementException();
     }
     Object returnValue = next;
     next = null;
     return returnValue;
   }

   public void remove() {
     throw new UnsupportedOperationException("No remove allowed");
   }
  }
}

//--------------

//--继承MyIterator的NewsIterator

//实现了resultToObject()

//--------------

package cn.edu.njut.jp.soso.model;

import com.mysql.jdbc.ResultSet;

public class NewsIterator extends MyIterator{
  protected  Object resultToObject(ResultSet rs) throws Exception{
    //测试代码
    System.out.println("在NewsIterator中!");
    News _news=new News();
    String strValue=null;
    strValue=rs.getString("newsID");
    if(strValue==null)
      throw new Exception("新闻ID为空!");
    _news.setNewsID(strValue);

    strValue=rs.getString("subject");
    if(strValue==null)
      throw new Exception("新闻标题为空!");
    _news.setSubject(strValue);

    strValue=rs.getString("url");
    if(strValue==null)
      throw new Exception("新闻URL为空!");
    _news.setUrl(strValue);

    strValue=rs.getString("creationDate");
    if(strValue==null)
      throw new Exception("新闻创建日期为空!");
    _news.setCreationDate(strValue);

    strValue=rs.getString("sort");
    if(strValue==null)
      throw new Exception("新闻类别为空!");
    _news.setSort(strValue);

    strValue=rs.getString("fromSite");
    if(strValue==null)
      throw new Exception("新闻来自站点为空!");
    _news.setFromSite(strValue);
    return _news;
  }
}

//--------index.jsp------

<%@ page contentType="text/html; charset=GB2312" %>
<%@ page language="java" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<logic:forward name="welcome"/>

//--------chinatopnewsinclude.jsp---------------

<%@ page contentType="text/html; charset=GB2312" %>
<%@ page import="cn.edu.njut.jp.soso.model.News" %>
<%@ page import="cn.edu.njut.jp.soso.model.NewsIterator" %>
<%@ page import="com.mysql.jdbc.ResultSet" %>
<%@ page import="java.util.Iterator" %>
<html>
<head>
<title>
chinatopnewsinclude
</title>
<link rel="stylesheet" href="css/font.css" type="text/css">
</head>
<body bgcolor="#FFFFFF">
<center>
  <table width="100%" border="0" cellspacing="5" cellpadding="0" class="font">
<%
News news=new News();
NewsIterator newsIterator=new NewsIterator();
Iterator iterator=newsIterator.resultToIterator((ResultSet)request.getAttribute("chinaNewsResult"));
System.out.println("网页中的:"+iterator.hasNext());
while(iterator.hasNext()){
news=(News)iterator.next();
%>
    <tr>
      <td width="33%">
        <div align="center">新闻标题</div>
      </td>
      <td width="33%">
        <div align="center">日期</div>
      </td>
      <td width="34%">
        <div align="center">来自网站</div>
      </td>
    </tr>
    <tr>
      <td width="33%"><%=news.getSubject()%></td>
      <td width="33%">date</td>
      <td width="34%">from</td>
    </tr>
<%
}

%>
  </table>
</center>
</body>
</html>

//-----Struts-congif.xml文件为

   <global-forwards>
    <forward   name="welcome"                path="/welcome.do"/>
  </global-forwards>


  <action-mappings>

    <!-- Enter into Welcome Page -->
    <action    path="/welcome"
               type="cn.edu.njut.jp.soso.controller.DisplayAllNewsAction">
      <forward name="success"              path="/chinatopnewsinclude.jsp"/>
    </action>

  </action-mappings>

出现的问题为:chinatopnewsinclude.jsp没有打印的新闻,可是我在

News中的System.out.println("新闻标题为:"+subject);却只能能打印

出两段新闻标题。数据库没有问题,超过两条记录。

banq
2002-10-11 17:46

这么一段长代码,建议你使用log4J 跟踪测试,这样你就可以知道问题所在了。