即使已经给出了List,List也不会添加其他ResultSet

时间:2017-05-24 03:53:55

标签: java jdbc

我在我的ResultSet中添加了所有List <EmployeeModel。我成功检索了所有行。但是当在List中添加所有行时,它只获取第一行,并且循环已经跳过要添加的另一行。有什么原因吗?

public void getStartEndTimeForOvertime(EmployeeModel employeeModel) 
{
    String query = "{call getStartEndTimeForOvertime(?,?)}";
    List <EmployeeModel> list = new ArrayList();

    try(Connection con = DBUtil.getConnection(DBType.MYSQL);
        CallableStatement cs = con.prepareCall(query);)
    {
        cs.setInt(1, EmployeeModel.getId());
        cs.setString(2, employeeModel.overtimeModel.getDay());

        try(ResultSet rs = cs.executeQuery())
        {
            while(rs.next())
            {
                employeeModel.overtimeModel.setStartTime(rs.getString(1));
                employeeModel.overtimeModel.setEndTime(rs.getString(2));

                list.add(employeeModel);
            }
        }

    }
    catch(SQLException ex)
    {
        System.out.println("Error at getStartEndTimeForOvertime: "+ex.getSQLState());
        System.out.println("Error at getStartEndTimeForOvertime: "+ex.getMessage());
        System.out.println("Error at getStartEndTimeForOvertime: "+ex.getErrorCode());
    }
}

1 个答案:

答案 0 :(得分:2)

在遍历resultSet时,每次在EmployeeModel的同一对象上设置它时 而是这样做

 while(rs.next()){
    EmployeeModel employeeModel = new EmployeeModel();
    employeeModel.overtimeModel.setStartTime(rs.getString(1));
    employeeModel.overtimeModel.setEndTime(rs.getString(2));

    list.add(employeeModel);
}