如何在循环while循环后将结果集重置为第一行

时间:2015-08-07 15:02:08

标签: java resultset

我的代码有两个循环,我的外循环应循环遍历外循环的第一行的内循环的所有行,而对于外循环的第二行,它应循环遍历所有的行内排。

int y1,y2;
float t = 0,s1,s2;

while(rm.next())
{
    int currentCol = 0;

    cellNumber = new jxl.write.Number (currentCol++, currentRow, index, integerFormat);
    index++;
    sheet.addCell ( cellNumber );

    cellLabel = new Label(currentCol++, currentRow, rs.getString("Name"));
    sheet.addCell ( cellLabel );


    y1 = rm.getInt("Year");

    System.out.println("Year 1: " +y1);


    cellNumber = new jxl.write.Number (currentCol++, currentRow, y1 , integerFormat);
    sheet.addCell ( cellNumber );



    s1 = rm.getFloat("Total_Price");
    System.out.println("S1: "+s1);

    while (rs.next())
    {
        y2 = rs.getInt("Year");
        System.out.println("Year 2: " +y2);

        s2 = rs.getFloat("Total_Price");
        System.out.println("S2: " +s2);

        if(y1==y2)
        {
            t = s1+s2;    
            System.out.println("Toatl Sales:" +t);

            cellNumber = new jxl.write.Number (currentCol++, currentRow, t , priceformat);
            sheet.addCell ( cellNumber );

        }


    } 
    int a = rs.getFetchDirection();
    System.out.println("Direction: " +a);

    rs.setFetchDirection(ResultSet.FETCH_REVERSE);


    cellNumber = new jxl.write.Number (currentCol++, currentRow, s1 , priceformat);
    sheet.addCell ( cellNumber );




    currentRow++;

}

3 个答案:

答案 0 :(得分:9)

使用此:

resultSet.beforeFirst()

来自docs:

  

抛出:   SQLException - 如果发生数据库访问错误;这个方法是   调用闭合的结果集或结果集类型是   TYPE_FORWARD_ONLY

答案 1 :(得分:1)

以下是您要找的内容:

rm.beforeFirst()

Official documentation

  

将光标移动到此ResultSet对象的前面,就在第一行之前。如果结果集不包含任何行,则此方法无效。

答案 2 :(得分:0)

使用

resultSet.beforeFirst();

但是您必须通过以下方式创建声明:

Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

因此它是可遍历的,而不仅仅是一个方向。