gpt4 book ai didi

java - int 值不在函数中返回?

转载 作者:行者123 更新时间:2023-11-30 02:08:26 24 4
gpt4 key购买 nike

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

最佳答案

不要将值赋给变量。如果您的代码没有找到任何合适的产品,它将毫无问题地执行并返回 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));
}

如果产品销售价格是强制性的,您也可以使用OptionalInt作为返回类型,将返回值替换为returnOptionalInt.of(... ),并使用 returnOptionalInt.empty() 进行抛出。如果它是一个抛出更好,因为它表明模型错误,您不应该轻易忽略。

尽管我想知道为什么您要使用 product_sell_price 列(它是 String 列类型)并将其解析为整数。这是一个风险。最好将列定义为数字类型。

关于java - int 值不在函数中返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50778154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com