迭代ResultSet并在ArrayList中添加其值 [英] Iterating over ResultSet and adding its value in an ArrayList
问题描述
我正在迭代 ResultSet
并尝试在 ArrayList
中复制其值。
问题是它的遍历只有一次。但是使用 resultset.getString(Col 1)
到 resultset.getString('Col n)
显示全部所有列的条目。
下面是代码片段 -
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 resultset.getString("Col 1")
to resultset.getString('Col n")
is showing all entries of all columns.
Below is the code snippet -
ResultSet resultset = null;
ArrayList<String> arrayList = new ArrayList<String>();
int i = 1;
while (resultset.next()) {
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 n"));
}
唯一值 ResultSet
被复制到 ArrayList
用于第1列。然后在退出时。
但我可以看到所有列的值。
为什么?
The only value of ResultSet
getting copied into ArrayList
is for column 1. And then while exits.
But I can see the value of all columns.
Why?
推荐答案
如果我理解你的问题,有两种可能问题在这里:
If I've understood your problem correctly, there are two possible problems here:
-
结果集
是null
- 我认为这不可能就像你在你的while循环中得到一个异常而没有输出任何东西 - 第二个问题是
resultset.getString(i ++)
将从每个后续行 获取列1,2,3等等
resultset
isnull
- I assume that this cant 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.
让我们说你只返回1行,如下所示
Lets say you only had 1 row returned, as follows
Col 1, Col 2, Col3
A , B, C
您的代码只能获得A - 它不会得到其余的列。
Your code as it stands would only get A - it wouldnt get the rest of the columns.
我建议您更改代码如下:
I suggest you change your code as follows:
ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>();
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"));
}
修改:
获取列数:
ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();
这篇关于迭代ResultSet并在ArrayList中添加其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!