gpt4 book ai didi

java - 方法向数据库语句返回空值

转载 作者:行者123 更新时间:2023-12-01 11:42:30 26 4
gpt4 key购买 nike

我在名为 ProductInsert 的类中有如下方法:

public float insertPrice() {
try {
System.out.println("Enter Product Price:");
setProductPrice(scanFloat.nextFloat());
}catch (InputMismatchException e){
System.out.println("Invalid Input!");
new ProductInsert().insertPrice();
}
return getProductPrice();
}

我有另一个名为 ProductServices 的类,具有以下准备好的语句数据库执行:

            PreparedStatement pstm = con.prepareStatement(insertQuery);
pstm.setFloat(2, insertPrice());

因此,当用户在询问价格时输入字符串值“asdfad”时,它会返回一个InputMismatch异常并再次调用insertPrice方法。在第二次调用时,用户输入浮点值“230.00”,pstm.setfloat 会获取空值,并在数据库中插入“0.00”而不是“230.00”。为什么???

产品价格的 setter 和 getter :

public float getProductPrice() {
return productPrice;
}

public void setProductPrice(float productPrice) {
this.productPrice = productPrice;
}

最佳答案

当出现异常时,您创建一个实例new ProductInsert().insertPrice();

首次调用 insertPrice() 时返回的值是来自此 ProductPrice 实例(您准备语句的实例)的值,该值未设置 (或设置为 0.0)。

catch中,直接调用insertPrice()而无需new ProductPrice(),但您肯定需要重置 或使用错误的输入,例如

 //...
catch (InputMismatchException e){
System.out.println("Invalid Input!");
scanFloat.nextLine(); // will "eat" the wrong entry
insertPrice(); // try again
}

关于java - 方法向数据库语句返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29418154/

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