int值不返回函数?

时间:2018-06-09 20:15:05

标签: java

我试图返回一个int变量,但它不起作用。我想在我的函数中返回变量product_price。请帮帮我。

  public static int getProductSellPriceById(int productid) {

        try {
            currentCon = ConnectionManager.getConnection();
            ps=currentCon.prepareStatement("select product_sell_price from products where product_id=?");

            ps.setInt(1, productid);
            ResultSet rs = ps.executeQuery(); 

            if (rs.next()) {
                int product_price = Integer.parseInt(rs.getString("product_sell_price"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return product_price;
   }

2 个答案:

答案 0 :(得分:1)

您可以直接从if条件中返回:

ggplot(predictions, aes(x, y)) +
  geom_point() +
  geom_line(aes(x, y.pred), colour = "red") +
  facet_wrap( ~ model + dataset_name, scales = "free")

您还可以将函数的返回类型更改为Integer,并返回null作为默认值,以表示未找到任何值。

答案 1 :(得分:1)

不要将值赋给变量。如果您的代码没有找到任何合适的产品,它将毫无问题地执行并返回0,就像它遇到数据库问题时一样,例如具有不同列的表。

另请注意,您需要清理数据库中正在使用的所有资源,否则很快就会耗尽连接。幸运的是,尝试使用资源非常容易。

我已将您的代码改编为应有的代码。

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));
}   

如果产品销售价格强制要求,您也可以使用OptionalInt作为退货类型,将退货替换为return OptionalInt.of(...),抛出return OptionalInt.empty() }。如果是抛出更好,因为它表示模型错误,你不应该轻易忽略。

虽然我想知道您为什么要使用product_sell_priceString列并将其解析为整数。这是一种风险。最好将列定义为数字类型。