循环遍历结果集以搜索不同表上的另一个值

时间:2017-01-31 14:05:42

标签: java sql jdbc

我想在Results表中搜索一些特定的结果,使用来自不同表的id来根据从studentInfo表中选择的学生ID来计算cgpa,下面是我尝试过的,问题是它只计算首先是Id或者更确切地说是学生

    String lev = levelCombo.getSelectedItem().toString();
    int leve = Integer.parseInt(lev);
    int le = leve / 100;
    try {
        String sql
                = "select idNumber from studentInfo where level ='" + lev + "'  ";

        pst = conn.prepareStatement(sql);
        rs = pst.executeQuery();
        while (rs.next()) {
            String idNumb = rs.getString("idNumber");
            cgpa(idNumb, le);
            System.out.print("" + idNumb);
        }
    } catch (Exception e) {
    }
}

public void cgpa(String idnumber, int level) {
    float units = 0;
    float ugps = 0;
    float cgp = 0;

    for (int i = 1; i <= level; i++) {
        try {

            String sql = "select sum(UNIT) ,sum(UGP) ,round(sum(UGP) / NULLIF(sum(UNIT), 0), 2) from Results where ID_NUMBER =  ? and  level ='" + i + "'  ";

            pst = conn.prepareStatement(sql);
            pst.setString(1, idnumber);
            rs = pst.executeQuery();
            while (rs.next()) {
                Float un = rs.getFloat("sum(UNIT)");
                Float gp = rs.getFloat("sum(UGP)");
                //  Float sum=rs.getFloat("round(sum(UGP)/NULLIF(sum(UNIT), 0),2)");
                units += un;
                ugps += gp;
                cgp = ugps / units;
                String sql1 = "update academicstatus set cgpa ='" + cgp + "'  ,product='" + ugps 
                        + "',unit='" + units + "' where idnumber = ? ";
                updateAcademicstatus(cgp, ugps, units, idnumber);
                pst = conn.prepareStatement(sql1);
                pst.setString(1, idnumber);
                pst.executeUpdate();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                rs.close();
                pst.close();
            } catch (Exception e) {
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您是否尝试进行单一查询

select  sum(UNIT),sum(UGP),round(sum(UGP)/ ULLIF(sum(UNIT),0),2)idNumber from studentInfo sinfo
join Results re on re.ID_NUMBER = sinfo.idNumber where level='"+lev+"'"

答案 1 :(得分:0)

您的Connection中存在问题,因此您在循环中使用:prepareStatement这会产生问题,因为您的语句不接近,因此您应该每次迭代关闭或创建一个新语句。

解决问题的最佳方法是创建一个分离的方法来执行以下操作:

updateAcademicstatus(cgp, ugps, units, idnumber);

所以updateAcademicstatus应该说出必要的参数,然后你可以像你一样进行更新,最后关闭你的陈述。

或者你可以使用addBatch所以在每次迭代中都像这样添加Batch()并最终执行你的语句:

while(...){
  //...
  pst.addBatch();
}
pst.executeBatch();

注意

而不是使用cgpa ='" + cgp + "'使用此cgpa = ?更安全,更有帮助

您可以详细了解Reusing a PreparedStatement multiple timesPrepared Statement doc