【问题标题】:int value in not return in function?int 值在函数中不返回?
【发布时间】:2018-11-19 13:09:53
【问题描述】:

我尝试返回一个 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;
   }

【问题讨论】:

  • try..catch块外声明int product_price = 0;//or any default value
  • 我想返回这个 Integer.parseInt(rs.getString("product_sell_price"))。
  • 有很多方法可以解决这个问题,只需在try and catch之外声明变量并使用product_price = Integer.parseInt(rs.getString("product_sell_price"));或者你可以使用return Integer.parseInt(rs.getString("product_sell_price"));并且在你关闭你的方法之前返回一个默认值

标签: java


【解决方案1】:

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

另外请注意,您需要从数据库中清理您正在使用的所有资源,否则您很快就会用完连接。幸运的是,try-with-resource 让这变得非常容易。

我已将您的代码调整为应有的样子。

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

如果 product-sellprice 是强制性的,您也可以使用 OptionalInt 作为返回类型,将返回替换为 return OptionalInt.of(...),并将 throw 替换为 return OptionalInt.empty()。如果是 throw 更好,因为它表示模型错误,您不应轻易忽略。

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

【讨论】:

  • 对不起,我还在编程。顺便说一句,谢谢伙计。
【解决方案2】:

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

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()) {
            return Integer.parseInt(rs.getString("product_sell_price"));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } 

    return 0; // or any other default value
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 2012-09-21
    • 2023-03-29
    相关资源
    最近更新 更多