【问题标题】:how to run Resultset.next() twice?如何运行Resultset.next() 两次?
【发布时间】:2016-02-22 22:15:08
【问题描述】:

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

另外,我必须做两次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() 中做到这一点 但我想做两次;)

【问题讨论】:

  • 你不能使用一个循环并将两个操作放在一个循环中吗?
  • 检查this 答案。
  • 为什么不能只循环一次呢?对于您显示的代码,单独计算这种方式没有意义。

标签: java sql oracle jdbc resultset


【解决方案1】:

你可以像下面这样初始化你的Statement

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

因此,您可以在语句中移动光标。

现在您可以循环遍历它。

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

但这是非常不必要的,最佳解决方案是直接跳到集合的末尾并返回该行

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

【讨论】:

    【解决方案2】:

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

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

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

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

    或者,

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

    【讨论】:

    • 你不能这样做,因为tmpRs_1tmpRs_2 仍然是同一个ResultSet
    猜你喜欢
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多