2

此代码返回除第一行之外的每一行。我看不出有什么问题?我怎样才能让它包括第一个?

stmt = con.createStatement();  

ResultSet res=stmt.executeQuery("SELECT * FROM Orders ORDER BY OrderID");

if (res.next())
{
    ResultSetMetaData rsmd=res.getMetaData();
    int columnCount=rsmd.getColumnCount();
    for (int i = 1; i<= columnCount; i++) {
        columnHeading=columnHeading+"\t"+rsmd.getColumnName(i); 
    }
    System.out.println(columnHeading);
    while(res.next()) {
        for (int i= 1; i<= columnCount; i++) {                            
            System.out.print("\t"+res.getString(i));
        }
    System.out.println("\n");
    }
}
4

5 回答 5

2

You're calling res.next() twice - once here:

if (res.next())

and once here:

while (res.next())

Between the if statement and the while statement, you're "looking at" the first row - but by the time you get into the while loop body, you're already on the second row.

The simplest fix would probably be to change:

while (res.next())
{
}

To:

do
{
} while (res.next());
于 2013-04-14T21:08:15.377 回答
0

ResultSet当你打电话时,你正在移动if(res.next)

这意味着当你进入你的循环时,你已经在下一排了。

将循环更改为 do-while

do {

} while (res.next());

这将在第一次循环调用之前next运行代码。

于 2013-04-14T21:09:06.870 回答
0

res.next()将自动移动结果集。您首先在if语句中调用它,然后在while打印任何行之前再次在语句中调用它,并且在打印任何内容之前调用它两次,您错过了第一行。

将 更改while为 a do..while,这应该如您所愿。

于 2013-04-14T21:09:38.790 回答
0

尝试这个。我希望它会奏效。

stmt = con.createStatement();  

ResultSet res=stmt.executeQuery("SELECT * FROM Orders ORDER BY OrderID");

if (res != null)
{
ResultSetMetaData rsmd=res.getMetaData();
int columnCount=rsmd.getColumnCount();
for (int i = 1; i<= columnCount; i++) {
    columnHeading=columnHeading+"\t"+rsmd.getColumnName(i); 
}
System.out.println(columnHeading);
while(res.next()) {
    for (int i= 1; i<= columnCount; i++) {                            
        System.out.print("\t"+res.getString(i));
    }
 System.out.println("\n");
 }
}
于 2013-04-15T15:06:23.497 回答
-1

这里的问题是 ResultSet 的索引不是从 0 开始的。因此,如果您没有全局声明 ResultSet,那么您必须按以下方式编写:ResultSet res = null; 否则它将起作用。

于 2017-04-23T02:41:57.280 回答