如何 运行 Resultset.next() 两次?

how to run Resultset.next() twice?

我有这个方法来获取一串行并打印它们。

此外,我还得做两次while(Resultset.next())。第一个是获取行数,第二个是打印字符串。但是当方法第一次运行时 Resultset.next() 方法跳过第二次 Resultset.next().

public static String[] gett() throws ClassNotFoundException, SQLException{

    // this for get conneced to the database .......................

    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hr","111"); 
    Statement st = conn.createStatement();
    ResultSet re = st.executeQuery("select location_id from DEPARTMENTS");

    // Ok , now i have the ResultSet ...

    // the num_row it's counter to get number of rows
    int num_row = 0;

    // this Arrar to store String values
    String[] n = new String[num_row];

    // this is the first ResultSet.next , and it's work ..!
    // also , this ResultSet.next work to get number on rows and store the number on 'num_row' 
    while(re.next())
        num_row++;

    // NOW , this is the secound 'ResultSet.next()' , and it's doesn't WORK !!!!
    while(re.next()) {
        System.out.println(re.getString("location_id"));
    }
}

问题是,第一个 Resultset.next() 工作正常,但第二个不工作!

有人可以解释为什么吗?我怎样才能让它发挥作用?

注意: 我知道,还有另一种方法可以做到这一点 Resultset.next() 但我想做两次 ;)

第二个 rs.next() 不工作,因为 rs 已经到达第一个循环的结束位置。

您可以将 re.next() 存储到临时变量中。

例如ResultSet tmpRs_1 = rs; ResultSet tmpRs_2 = rs;

然后将这两个变量用于两个循环。

或者,

您可以在一个循环中完成所有操作。这样你就不需要两个循环了。

您可以按以下方式初始化您的 Statement

conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

因此,您可以在声明中四处移动光标。

现在您可以循环遍历它。

while(re.next())
    num_row++;
re.beforeFirst();

但这完全没有必要,最佳解决方案是直接跳到集合的末尾,return 行

num_row = 0;
if(re.last()) {
   num_row = rs.getRow();
   re.beforeFirst();
}