Iterating over ResultSet and adding its value in an ArrayList

前端 未结 2 1890
醉梦人生
醉梦人生 2020-12-08 15:18

I am iterating over an ResultSet and trying to copy its values in an ArrayList. The problem is that its traversing only once. But using resul

2条回答
  •  清歌不尽
    2020-12-08 15:49

    If I've understood your problem correctly, there are two possible problems here:

    • resultset is null - I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.
    • The second problem is that resultset.getString(i++) will get columns 1,2,3 and so on from each subsequent row.

    I think that the second point is probably your problem here.

    Lets say you only had 1 row returned, as follows:

    Col 1, Col 2, Col 3 
    A    ,     B,     C
    

    Your code as it stands would only get A - it wouldn't get the rest of the columns.

    I suggest you change your code as follows:

    ResultSet resultset = ...;
    ArrayList arrayList = new ArrayList(); 
    while (resultset.next()) {                      
        int i = 1;
        while(i <= numberOfColumns) {
            arrayList.add(resultset.getString(i++));
        }
        System.out.println(resultset.getString("Col 1"));
        System.out.println(resultset.getString("Col 2"));
        System.out.println(resultset.getString("Col 3"));                    
        System.out.println(resultset.getString("Col n"));
    }
    

    Edit:

    To get the number of columns:

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

提交回复
热议问题