Answer the question
In order to leave comments, you need to log in
JDBC how to fetch all records as one object?
JDBC how to fetch all records as one object?
let's say I take everything I need from the database like this (query is a variable with an SQL query), ResultSet rs = st.executeQuery(query);
but I don't want to build such a structure every time
while (rs.next()) {
System.out.println(rs.getString("id"));
System.out.println(rs.getString("name"));
}
Answer the question
In order to leave comments, you need to log in
Made it this way:
private ArrayList<HashMap<String, Object>> resultSetToArrayList(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
ArrayList<HashMap<String, Object>> list = new ArrayList<>();
while (rs.next()) {
HashMap<String, Object> row = new HashMap<>(columns);
for (int i = 1; i <= columns; ++i) {
row.put(md.getColumnName(i), rs.getObject(i));
}
list.add(row);
}
return list;
}
ArrayList<HashMap<String, Object>> list = resultSetToArrayList(rs);
for (HashMap<String, Object> row : list) {
System.out.println(row.get("id"));
System.out.println(row.get("name"));
}
Well, apparently you need to make an array and write all the data into it in a loop, so that you can use it anywhere later.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question