谢谢,异常的问题我解决了,是我一时没想清楚。现在有新问题了。我用了你介绍的那个方法,iterator,不知道是否是我的程序的问题,得到的iterator是空的。下面是搜索的一个方法
public Iterator getSearchbyKind(short kindid,String ip){
Connection con = null;
PreparedStatement pst = null;
String sql = null;
try {
con = MysqlConn.getConnection(ip);//这里是正确的
sql = "select l.lawid,l.lawname,l.lawcontent,l.subkindid,l.kindid,k.kindname,l.bbtime,l.sstime,l.sxtime,l.unit,l.note from Law l,Kind k where l.kindid=k.kindname and l.kindid=?";//我会给一个常量2,应该有2个记录符合要求
pst = con.prepareStatement(sql);
pst.setShort(1,kindid);
System.out.println("sql=select l.lawid,l.lawname,l.lawcontent,l.subkindid,l.kindid,k.kindname,l.bbtime,l.sstime,l.sxtime,l.unit,l.note from Law l,Kind k where l.kindid=k.kindname and l.kindid="+kindid);
final ResultSet rs = pst.executeQuery();
searchrowcount=0;
return new Iterator() {
private Law law;
public boolean hasNext() {
if (law == null) {
try {
if (! rs.next()) {
return false;
}
searchrowcount++;//计算一下有多少个元素
law.LawId = rs.getShort("lawid");
law.LawName =rs.getString("lawname");
law.LawContent = rs.getString("lawcontent");
law.SubKindId =rs.getShort("subkindid");
law.KindId=rs.getShort("kindid");
law.KindName = rs.getString("kindname");
law.BbTime=rs.getDate("bbtime");
law.SsTime =rs.getDate("sstime");
law.Sxtime =rs.getDate("sxtime");
law.Unit = rs.getString("unit");
law.Note =rs.getString("note");
}catch(Exception e){e.printStackTrace();return false;}
}
return true;
}
public Object next() {
if (! hasNext()) {
throw new NoSuchElementException();
}
Law retval = law;
law = null;
return retval;
}
public void remove() {
throw new UnsupportedOperationException("no remove allowed");
}
};
}catch(Exception e){
e.printStackTrace();
return null;
}
finally {
try { pst.close(); } catch(SQLException ne) { ne.printStackTrace(); }
try { con.close(); } catch(SQLException ne) { ne.printStackTrace(); }
}
}
我在另一个java中调用上面的方法,这是调用上面方法的函数
public void search(){
LawConnBean LawConn = new LawConnBean();//这个构造函数可以调用上面的方法
Iterator i_law =LawConn.getSearchbyKind((short)2,ip);
try{
System.out.println(i_law.hasNext());//得到false
while (i_law.hasNext()){
System.out.println("Law="+((Law)i_law.next()).LawName);
}
System.out.println("count="+LawConn.getSearchrowcount());//得到count=0
}catch(Exception e){e.printStackTrace();}
}
我在getSearchbyKind((short)2,ip)里面给了一个固定的2,应该得到有2条记录,但是结果却是空值。