没有得到结果集中的所有行

时间:2013-06-11 05:45:07

标签: java resultset

我使用以下代码从结果集中的数据库中获取数据:

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());   

Connection connection = DriverManager.getConnection(
                    "jdbc:oracle:thin:@host:1521:DB", "User","pass_01");
Statement statement = connection.createStatement();   
resultset = statement.executeQuery("select * from employee"); 
System.out.println("Records Exist "+resultset.next()); 
System.out.println(resultset.getRow());
while (resultset.next()) {
    System.out.println(resultset.getInt(1) + " " +
    resultset.getInt(2) + " " + 
    resultset.getInt(3) + " " + 
    resultset.getString(4));
}

但是我只获得了一行,尽管数据库表中有两行。我在这里缺少什么?

3 个答案:

答案 0 :(得分:8)

这是因为你在循环之前调用了rs.next()。它返回一个布尔值,由于这个语句,一行失去了打印的机会。

Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@host:1521:DB", "User","pass_01");
Statement statement = connection.createStatement();   
resultset = statement.executeQuery("select * from employee"); 
while (resultset.next()) {
    System.out.println(resultset.getInt(1) + " " +
    resultset.getInt(2) + " " + 
    resultset.getInt(3) + " " + 
    resultset.getString(4));
}

答案 1 :(得分:0)

打印时取下ResultSet.next()。这使得RS光标指向新行

答案 2 :(得分:0)

我遇到了同样的问题,我通过使用 do...while 循环而不是 while 来解决它。你也可以试试这个。