【问题标题】:rs.last() gives Invalid operation for forward only resultset : lastrs.last() 为仅转发结果集提供无效操作:最后
【发布时间】:2012-02-18 21:26:08
【问题描述】:

我正在尝试通过以下方式获取结果集的行数:

rs.last();
int row_count = rs.getRow();

但我收到Invalid operation for forward only resultset : last 错误。结果集从 Oracle 10g 数据库中获取数据。

这是我设置连接的方式:

    Class.forName("oracle.jdbc.driver.OracleDriver");
    String connectionString = "jdbc:oracle:thin:@" + oracle_ip_address + ":" + oracle_db_port + ":" + oracle_db_sid;
    Connection conn = DriverManager.getConnection(connectionString, oracle_db_username, oracle_db_password);

【问题讨论】:

    标签: java oracle jdbc resultset


    【解决方案1】:
    PreparedStatement ps = conn.prepareStatement ("SELECT * FROM
             EMPLOYEE_TABLE WHERE LASTNAME = ?" ,
             ResultSet.TYPE_SCROLL_INSENSITIVE , 
             ResultSet.CONCUR_UPDATABLE ,
             ResultSet.HOLD_CURSOR_OVER_COMMIT) ;
    

    对于prepared statements,您必须至少指定类型last()isLast() 工作的并发模式。

    【讨论】:

    • isLast() 不需要光标可滚动。 last() 需要它。
    • @isaac.hazan,不适用于任何驱动程序:stackoverflow.com/questions/10597068/…
    • ResultSet.CONCUR_UPDATABLE 不建议用于商业项目。请尽可能避免。
    【解决方案2】:

    ResultSet.last() 和其他“绝对索引”查询操作仅在结果集可滚动时可用;否则,您只能逐一遍历 forward-only 结果集。

    以下示例(来自the javadocs)演示了如何创建可滚动的ResultSet

    Statement stmt = con.createStatement(
        ResultSet.TYPE_SCROLL_INSENSITIVE,
        ResultSet.CONCUR_READ_ONLY
    );
    ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
    

    请记住,使用可滚动查询会影响性能。如果此特定 ResultSet 的目标只是获取其最后一个值,请考虑优化您的查询以仅返回该结果。

    【讨论】:

    • 根据最新的规范,我们必须在 createStatement() 中添加两个参数 - Statement statement = con.createStatement(resultSetType, resultSetConcurrency); 如cheheen 所述,我们必须传递 ResultSet.TYPE_SCROLL_INSENSITIVE 但我们还必须再传递一个参数 - 请参考这个 - resultSetType a result set type; one of ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, or ResultSet.TYPE_SCROLL_SENSITIVE resultSetConcurrency a concurrency type; one of ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE
    • 当我尝试执行Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE ); 时,请帮我说The method createStatement() in the type Connection is not applicable for the arguments (int)
    • @StringForever 指的是 PareshKumar 提到的内容。
    • @danielad 实际上,该方法签名一直需要两个参数。原来的代码总是不正确的。我现在已更正它(并更新了损坏的链接)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 2022-07-16
    • 2018-10-17
    • 2013-05-26
    相关资源
    最近更新 更多