2

我在 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;

现在它返回如下内容:

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

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

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

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

2 回答 2

7

像这样:

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
}
于 2013-08-19T16:08:28.723 回答
0
    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");
    }
于 2014-02-19T12:38:43.110 回答