1

I have an application which gets data from database and create excel. I wanted to separete dao class which gets the resultSet from db and the class which is creating excel with this resultset.

In this way I was passing ResultSet from Dao to the other class to create excel file. But when I run the rs.next(), it gives me "Closed Resultset:next" error. I read on the internet that passing ResultSet is not good idea therefore I just try to do it in dao class and it worked.

But in that way I do not like to do other task (creasting excel) in dao class and I do not want to create a class and then send them as a list. So my question is why it is bad to pass resultset to other class or function? Why I got exception when I pass it and try to call rs.next()?

To Summarize my code looks like these:

ResultSet rs = myDao.getResult();
ExcelCreator excelCreator = new ExcelCreator();
excelCreator.createExcel(rs);
user1474111
  • 1,356
  • 3
  • 23
  • 47
  • check if in your DAO class you are closing the connection, because closing connection may also lead to closing ResultSet – Rajesh Jangid Apr 15 '16 at 12:37

2 Answers2

1

Because it may lead to resource leaking by forcing connection open and closing connection causes closing result set. Hence we use collection of Objects to return it.

BhanuReddy
  • 74
  • 10
1

Why you are getting "Closed resultset:next" error, see here:

Why am I getting ResultSet is closed error when I never closed any

I suppose you are not using some ORM framework like Hibernate.

In this case, map the resultset data in the DAO or build an object mapper yourself, which maps the ResultSet to a some Data Transfer Object. Then pass this object to the createExcel() method.

Something like this:

ResultSet rs = myDao.getResult();
List<ExcelDto> excelDtos = new ArrayList<>();
ExcelDto excelDto;
while (rs.next()) {      
    excelDto = new ExcelDto();    
    dto.setXCol(rs.getString("XColumn"))
    excelDtos.add(dto);  
}
excelCreator.createExcel(excelDtos);

Then in the excelCreator you can work with an ArrayList instead of ResultSet.

Community
  • 1
  • 1
clementino
  • 307
  • 1
  • 12