【问题标题】:Accessing elements of a ResultSet with only one tuple, returns exceptions仅使用一个元组访问 ResultSet 的元素,返回异常
【发布时间】:2014-09-28 05:37:46
【问题描述】:

当我执行以下操作时:

public Product getProductById(long productId) throws DaoException {

    Connection con = DBManager.connect();
    PreparedStatement statement = null;
    ResultSet rs = null;
    try {
        statement = con.prepareStatement(QUERY_PROD_BY_ID);
        statement.setLong(1, productId);

        rs = statement.executeQuery();
        //rs.first();
        Product product = new Product();

        product.setProductId(rs.getLong("product_id"));
        product.setProductImage(rs.getString("image"));
        product.setProductBrand(rs.getString("brand"));
        product.setProductModel(rs.getString("model_no"));
        product.setProductPrice(rs.getFloat("price"));
        product.setProductSummary(rs.getString("summary"));
        product.setProductStock(rs.getInt("stock"));
        product.setProductCategory(rs.getLong("category_id"));
        product.setProductCreationTime(rs
                .getTimestamp("product_creation_time"));
        product.setProductStatus(ProductStatusState.values()[rs
                .getInt("product_status")]);
        product.setType(ProductType.values()[rs.getInt("type")]);

        return product;
    } catch (SQLException e) {
        throw new DaoException(e);

    } finally {
        DBManager.closeAll(statement, rs);

    }
}

我收到一个错误,上面写着

 org.postgresql.util.PSQLException: ResultSet not positioned properly, perhaps you need to call next.

我的 ProductId 是我的主键,因此 ResultSet 中只会出现一行。当我设置一个

while(rs.next){...}

它返回 null。我该怎么办?

【问题讨论】:

  • 显然你必须做 rs.next()。当你得到空值时你能显示代码吗
  • 第一次从任何新打开的 ResultSet 读取时,必须调用 next() 才能将 ResultSet 指针移到第一条记录上。

标签: java postgresql jdbc resultset


【解决方案1】:

如前面的 cmets 所述,当您执行返回结果集的查询时,游标的初始位置在结果集中的第一行数据之前。调用 rs.next() 会将光标移动到第一行,并允许您访问使用 rs.getXXX() 方法返回的数据。

【讨论】:

    猜你喜欢
    • 2014-12-31
    • 2014-07-28
    • 2022-07-11
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    相关资源
    最近更新 更多