如何在Java中的SqlRowSet.Next()上修复“无效的Cursor SQL异常”

时间:2019-01-15 15:31:04

标签: java spring spring-jdbc

从H2-数据库获取SqlRowSet对象之后,在使用SqlRowSet.getDouble();从行中检索数据之前,我叫SqlRowSet.next();

我尝试做while(SqlRowSet.next()){},但这不是必需的,因为我在数据中总是只有1行。

public SqlRowSet findBySkuSize(String sku, String size) {
    return jdbcTemplate.queryForRowSet("SELECT * from PRODUCT_DIMENSIONS where SKU = '" + sku + "' and SIZE = '" + size + "'");
}

以上方法填充了SqlRowSet对象(在调试器中,我可以看到下图中显示了1行。

        if(CountRows(dimensionResults) < 1) 
        {

        }
        else 
        {
            dimensionResults.next();
            someObject.objectSetterMethod(dimensionResults.getDouble("DEPTH"));

        }

上面的代码是引发InvalidCursorException的原因 我猜堆栈跟踪太长,无法粘贴,但这是错误消息

Caused by: java.sql.SQLException: Invalid cursor position
at com.sun.rowset.CachedRowSetImpl.next(CachedRowSetImpl.java:1460)
at org.springframework.jdbc.support.rowset.ResultSetWrappingSqlRowSet.next(ResultSetWrappingSqlRowSet.java:697)
... 67 more

org.springframework.jdbc.InvalidResultSetAccessException: Invalid cursor position; nested exception is java.sql.SQLException: Invalid cursor position
at org.springframework.jdbc.support.rowset.ResultSetWrappingSqlRowSet.next(ResultSetWrappingSqlRowSet.java:700)
at com.footlocker.commerce.shipping.service.FreightCalculationService.UpdateProductDimensions(FreightCalculationService.java:72)
at com.footlocker.commerce.shipping.service.FreightCalculationService.UpdateProductList(FreightCalculationService.java:50)
at com.footlocker.commerce.shipping.service.FreightCalculationService.ProcessFreightCalculationRequest(FreightCalculationService.java:41)
at com.footlocker.commerce.shipping.controller.FreightController.Test(FreightController.java:34)

Debugger

由于某种原因,它告诉我我的cursorPosition位于2?它应该从0开始吗?如果我只有1行,怎么可能是2。

编辑:我能够将调试器菜单中的光标位置从2更改为0,并且DimensionResults.next();为什么呢?为什么当我实例化对象时,它从光标位置2开始?对于为什么Java与C#相比如此复杂,以及要找到使一切都变得有意义的资源,我感到十分困惑。

1 个答案:

答案 0 :(得分:1)

显然,您的CountRows方法将您带到了结果集的末尾。

在这种情况下,您可能想调用beforeFirst()返回到结果集的初始位置。

cf。 how to reset the result set to the first row after looping through a while loop

您的位置2也是浏览resulset之后的位置,这是“最后一个”位置,与调用afterLast()之后的位置相同。

最后,您可能想看看以下问题: How do I get the size of a java.sql.ResultSet?