關於for迴圈的跳出問題技巧及資料集的處理方式
如圖所示:對結果集的操作主要步驟如下
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; //注意這是重點
}
p.setList(org_Info_list);
}
return p;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
如上所示:註釋行去掉程式就會在迴圈裡重複讀取某一行資料直到報錯,這時要讀取下一行資料就得跳出for 到while中
這時如註釋行:對i索引操作使其條件自相矛盾跳出迴圈重而達到目的