How can I retrieve a JDBC ResultSet as an ArrayList?

前端 未结 3 1782
有刺的猬
有刺的猬 2020-12-25 15:40

I\'m doing a query to retrieve a large amount of IDs (integers). Instead of iterating millions of times through the ResultSet and copying everything one-by-one to an ArrayLi

3条回答
  •  失恋的感觉
    2020-12-25 16:15

    Put the code in a method. It's very simple to call methods...

    Off the top of my head:

    public static List readInts(
         PreparedStatement statement
    ) throws SQLException {
         ResultSet results = statement.executeQuery();
         try {
             assert results.getMetaData().getColumnCount() == 1;
    
             List ints = new ArrayList();
             while (results.next()) {
                 ints.add(Integer.valueOf(results.getInt(1)));
             }
             return ints;
         } finally {
             results.close();
         }
    }
    

    Then just call it as:

    List ids = readInts(myStatemnet);
    

    Done.

提交回复
热议问题