C
C
ClaraOswald2016-05-26 18:03:55
MySQL
ClaraOswald, 2016-05-26 18:03:55

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"));
        }

because I don't know how many times I'll need them.
can you pick them up, for example, in the form of an array of objects or in any other more convenient form?
PS if something is wrong, I ask you not to throw faeces, because I'm just getting acquainted with java

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
coden55, 2016-05-26
@ClaraOswald

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"));
        }

A
Alexander Aksentiev, 2016-05-26
@Sanasol

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 question

Ask a Question

731 491 924 answers to any question