从java中的结果集中返回arraylist的arraylist

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18318256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:26:41  来源:igfitidea点击:

returning an arraylist of arraylist from a resultset in java

javasqlarraylistprepared-statementresultset

提问by Joey Hipolito

I created a database wrapper class in java and created a method called fetchAll(query).

我在 java 中创建了一个数据库包装器类并创建了一个名为fetchAll(query).

this.openConnection();

ArrayList<String> results = new ArrayList<String>();
PreparedStatement stmt = this.conn.prepareStatement(query);
ResultSet resultset = stmt.executeQuery();

ResultSetMetaData metadata = resultset.getMetaData();
int numcols = metadata.getColumnCount();

while (resultset.next()) {
    int i = 1;
    while (i < numcols) {
        results.add(resultset.getString(i++));
    }
}

this.closeConnection();

return results;

Now it returns something like this:

现在它返回如下内容:

[1, name1, address1, age1, 2, name2, address2, age2, 2, name2, address2, age3]

Which I found odd and the method does not return all columns, it lacks 1 column, why is it?

我发现这很奇怪,并且该方法没有返回所有列,它缺少 1 列,这是为什么?

How can I achieve something like this

我怎样才能实现这样的目标

[
  [1,name1,address1,age1,bday1],
  [2,name2,address2,age2,bday2],
  [3,name3,address3,age3,bday3]
]

采纳答案by jlordo

Like this:

像这样:

List<List<String>> result = new ArrayList<>();  // List of list, one per row
...
while (resultset.next()) {
    List<String> row = new ArrayList<>(numcols); // new list per row
    int i = 1;
    while (i <= numcols) {  // don't skip the last column, use <=
        row.add(resultset.getString(i++));
    }
    result.add(row); // add it to the result
}

回答by user3328044

    ResultSet resultset = statement.executeQuery(sql);//from DB      
    int numcols = resultset.getMetaData().getColumnCount();
    List <List <String> > result = new ArrayList<>();

    while (resultset.next()) {
        List <String> row = new ArrayList<>(numcols); // new list per row

        for (int i=1; i<= numcols; i++) {  // don't skip the last column, use <=
            row.add(resultset.getString(i));
            System.out.print(resultset.getString(i) + "\t");
        }
        result.add(row); // add it to the result
        System.out.print("\n");
    }