对于foreach循环java中的循环

时间:2017-07-07 11:01:32

标签: java database postgresql for-loop

所以我有这段代码。 searchStudentWith2RUCode()返回Student对象的Arraylist。学生对象具有各种属性,如forename,lastname,cprnumber,gpa等。

 public void assignStudents() throws ClassNotFoundException, SQLException {
     ArrayList<Student> notYetAssignedStudents = searchStudentsWith2RUCode();
     ArrayList<Student> assignedStudents = new ArrayList<>()
          for (Education edu : eduList) {

               for (int i = 0; i < edu.getAmountOfFreeSpacesInEdu(); i++) {
                  assignedStudents.add(notAssignedStudents.get(i));                      
                  setAssignedStudentsAdmitted(assignedStudents.get(i).getCPR, assignedStudents.get(i).getPrio, assignedStudents.get(i).eduNumber)
        }
    }
}

setAssignedStudentsAdmitted更新了我的数据库,应该设置字段&#34; sagsbehandling&#34;在我的桌子上&#34;学生&#34; as&#34; Optaget&#34;在每个录取的学生。然而,这不起作用。 我怀疑我的for循环,但我输了,我无法弄清楚它为什么不起作用。

这是我的setAssignedStudentsAdmitted方法:

 public void setAssignedStudentsAdmitted(String CPR, int prio, int eduNumber) throws ClassNotFoundException, SQLException {

    //Declare a UPDATE statement
    String updateStmt
            = "UPDATE Students SET sagsbehandling='Optaget' WHERE cprnr ='" + CPR + "' AND prio='" + prio + "' AND eduNumber='" + eduNumber + "';";

    //Execute UPDATE operation
    try {
        DatabaseController.dbExecuteUpdate(updateStmt);
    } catch (SQLException e) {
        System.out.print("Error occurred while DELETE Operation: " + e);
        throw e;
    }
}

}

这是我在setAssignedStudentsAdmitted中调用的dbExecuteUpdate方法

    public static void dbExecuteUpdate(String sqlStmt) throws SQLException, ClassNotFoundException {
    //Declare statement as null
    Statement stmt = null;
    try {
        //Connect to DB (Establish Postgres Connection)
        databaseConnect();
        //Create Statement
        stmt = conn.createStatement();
        //Run executeUpdate operation with given sql statement
        stmt.executeUpdate(sqlStmt);
    } catch (SQLException e) {
        System.out.println("Problem occurred at executeUpdate operation : " + e);
        throw e;
    } finally {
        if (stmt != null) {
            //Close statement
            stmt.close();
        }
        //Close connection
        databaseDisconnect();
    }
}

它成功构建,但在我的数据库中没有任何更改。

2 个答案:

答案 0 :(得分:0)

可能你有autoCommit设置为false?确保在您的databaseConnect()上,或者为了快速测试,最后执行Commit。

答案 1 :(得分:0)

//Declare a UPDATE statement
    String updateStmt
            = "UPDATE Students SET sagsbehandling='Optaget' WHERE cprnr ='" + CPR + "' AND prio='" + prio + "' AND eduNumber='" + eduNumber + "';";

范围updateStmtsetAssignedStudentsAdmitted方法范围内。那么,你如何在下面的方法调用中传递它?

 public static void dbExecuteUpdate(String sqlStmt) 
         throws SQLException, ClassNotFoundException {