Don't assign the value to a variable. If your code doesn't find any appropriate product it will execute without a problem and return 0
, just like it will when it hits a database problem, such as the table having different columns.
Also be aware that you need to clean up any resources you are using from the database, otherwise you'll run out of connections real soon. Luckily try-with-resource makes that very easy.
I've adapted your code to what it should be.
public int getProductSellPriceById(int productId) throws SQLException, NoSuchElementException {
try (Connection currentCon = ConnectionManager.getConnection();
PreparedStatement ps = currentCon.prepareStatement("select product_sell_price from products where product_id=?")) {
ps.setInt(1, productId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return Integer.parseInt(rs.getString("product_sell_price"));
}
}
}
throw new NoSuchElementException(String.format("No product with id %d found", productId));
}
If the product-sellprice is not mandatory you could also use OptionalInt
as a return type, replace the return with return OptionalInt.of(...)
, and the throw with return OptionalInt.empty()
. If it is a throw is better as it indicates a model error which you should not lightly ignore.
Although I wonder why you'd use a product_sell_price
column that is a String
column type and parse it into an integer. That is a risk. Better define the column to be a number type.