当我执行以下操作时:
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。我该怎么办?
答案 0 :(得分:1)
如前面的注释所述,当您执行返回结果集的查询时,游标的初始位置在结果集中的第一行数据之前。调用rs.next()会将光标移动到第一行,并允许您访问使用rs.getXXX()方法返回的数据。