简体   繁体   English

从多个结果集中将数据检索到单个Java列表中

[英]Retrieving data from multiple resultsets into a single java list

I have following three resultsets and a list. 我有以下三个结果集和一个列表。 How can i iterate the three resultsets without using three while(rs1.next()) and return the data to the list. 我如何不使用三个while(rs1.next())来迭代三个结果集并将数据返回到列表。

public Optional<List<StudentDetails>> getStudDetails(String id)
    {
        List<StudentDetails> stud= new ArrayList<StudentDetails>();
        ResultSet rs1 = (ResultSet) storedProcedureCall.getObject(4);
        ResultSet rs2 = (ResultSet) storedProcedureCall.getObject(5);
        ResultSet rs3 = (ResultSet) storedProcedureCall.getObject(6);

    }

If the goal is to avoid writing the same code for all ResultSet s (3 loops) you could create a method that loops through a ResultSet , generates StudentDetails objects for each row and adds those to a list. 如果目标是避免为所有ResultSet编写相同的代码(3个循环),则可以创建一个遍历ResultSet的方法,为每一行生成StudentDetails对象,并将这些对象添加到列表中。

Here is an example: 这是一个例子:

public Optional<List<StudentDetails>> getStudDetails(String id){
    List<StudentDetails> stud= new ArrayList<StudentDetails>();
    ResultSet rs1 = (ResultSet) storedProcedureCall.getObject(4);
    ResultSet rs2 = (ResultSet) storedProcedureCall.getObject(5);
    ResultSet rs3 = (ResultSet) storedProcedureCall.getObject(6);
    addStudentDetails(stud, rs1);
    addStudentDetails(stud, rs2);
    addStudentDetails(stud, rs3);
}

private static void addStudentDetails(List<StudentDetails> list, ResultSet rs){
    while(rs.next()){
        list.add(new StudentDetails(rs.get.....));
    }
}

If the resultset contains only a single object, then you dont need to go for loops. 如果结果集仅包含一个对象,则无需进行循环。 Instead use simple if statements to check if the data is available. 而是使用简单的if语句检查数据是否可用。

Something like: 就像是:

if(resultSet.hasNext()){
   Object obj= objresultSet.next();
}

do this for all of your ResultSet Objects 对您所有的ResultSet对象执行此操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM