This is really a bad idea. This approach requires that the connection is open the whole time until the last row is read and outside the DAO layer you never know when it will happen and you also seem to leave the resultset open and risk resource leaks and application crashes in the case the connection times out. You don't want to have that.
The normal JDBC practice is that you acquire Connection
, Statement
and ResultSet
in the shortest possible scope. The normal practice is also that you map multiple rows into a List
or maybe a Map
and guess what, they do have an Iterator
.
public List<Data> list() throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<Data> list = new ArrayList<Data>();
try {
connection = database.getConnection();
statement = connection.createStatement("SELECT id, name, value FROM data");
resultSet = statement.executeQuery();
while (resultSet.next()) {
Data data = new Data();
data.setId(resultSet.getLong("id"));
data.setName(resultSet.getString("name"));
data.setValue(resultSet.getInteger("value"));
list.add(data);
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return list;
}
And use it as follows:
List<Data> list = dataDAO.list();
int count = list.size(); // Easy as that.
Iterator<Data> iterator = list.iterator(); // There is your Iterator.
Do not pass expensive DB resources outside the DAO layer like you initially wanted to do. For more basic examples of normal JDBC practices and the DAO pattern you may find this article useful.