如图所示:对结果集的操作主要步骤如下
String sql = "select * from emp";
pstmt = conn.prepareStatement(sql);
//第四步,返会结果集
rs = pstmt.executeQuery();
while (rs.next()) {
int ID = rs.getInt("ID");
String org_code = rs.getString("org_code");
String org_name = rs.getString("org_name ");
String org_count = rs.getString("org_count");
}
这样就能够得到各个字段的值进而对各字段进行操作,这是jdbc提供的处理方法
但如果情况如下使用Hibernate查询返回的List 需要对其用Iterator遍历拆解在放入到实体中
代码如下:
public Pagination queryOrg_InfoCount(int siteId,int areaId ,String orgName, int pageNo, int pageSize) {
ArrayList<Org_Info> org_Info_list = new ArrayList();
Org_Info bmsg=null;
String sql="";
try {
if(areaId!=0)
{
if(orgName!=null)
{
sql="select a.id,a.org_code,a.org_name,(select count(*) from llt_report b where b.send_org_id=a.id) as org_count from llt_org_info a where a.area_code="+ areaId + " and (a.org_name like '"+ orgName+ "' or a.org_code like '"+orgName+"') order by org_count desc";
}
else
{
sql="select a.id,a.org_code,a.org_name,(select count(*) from llt_report b where b.send_org_id=a.id) as org_count from llt_org_info a where a.area_code="+ areaId + " order by org_count desc";
}
}
else
{
sql="select a.id,a.org_code,a.org_name,(select count(*) from llt_report b where b.send_org_id=a.id) as org_count from llt_org_info a order by org_count desc";
}
Query query =getSession().createSQLQuery(sql);
int totalCount = query.list().size();
Pagination p = new Pagination(pageNo, pageSize, totalCount);
query.setFirstResult(p.getFirstResult());
query.setMaxResults(p.getPageSize());
List list =query.list();
Iterator it=list.iterator();
Object [] results;
while(it.hasNext())
{
bmsg = new Org_Info();
results=(Object[]) it.next();
for(int i=0;i<results.length;i++)
{
bmsg.setId(Integer.parseInt(results[i].toString()));
bmsg.setOrg_code(results[i+1].toString());
bmsg.setOrg_name(results[i+2].toString());
bmsg.setFource_count(results[i+3].toString());
i = i + results.length - 1; //注意这是重点
org_Info_list.add(bmsg);
}
p.setList(org_Info_list);
}
return p;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
如上所示:注释行去掉程序就会在循环里重复读取某一行数据直到报错,这时要读取下一行数据就得跳出for 到while中
这时如注释行:对i索引操作使其条件自相矛盾跳出循环重而达到目的