-1

I have a table of two SQL columns, (name and address).

I want show the first and second data of the second column.

I am using this code

while (res.next()){
 System.out.print(res.getString(2))
}

But it gives me the all of second column How can i show the first and second data

4

3 回答 3

1

您在方法中看到的索引getString是列索引。所以:

while (res.next()){
    System.out.print(res.getString(1) + " " + res.getString(2));
}
于 2013-06-14T15:46:10.737 回答
0

但它给了我第二列的所有内容我如何显示第一和第二个数据

->这是因为您在有任何数据时创建了循环,请打印它。

因此,如果您只想打印前两行,则需要创建一些帮助变量 eq

int index = 0;
while (res.next() && index < 2) {
   System.out.print(res.getString("name"));
   System.out.print(res.getString("address"));
   index++;
}

注意:我建议您使用列名而不是索引。通过这种方式,您将避免不正确索引的问题(通常的错误)。

于 2013-06-14T15:51:00.780 回答
0

我假设你的意思是你只想要前两行?

只需计算您输出了多少行,并尽早结束循环。通过使用 while .. next 循环作为示例代码,如果ResultSet只有零行或一行,您可以避免出现问题。

int rowsOutput = 0;
while( res.next()) {
    System.out.println(res.getString(2));
    rowsOutput ++;
    if( rowsOutput >= 2) {
        break;
    }
}

或者,LIMIT在您的 SQL 中添加一个子句以仅选择前两行。

于 2013-06-14T15:46:09.077 回答