我在购买产品时,在数据库中增加产品数量时遇到一些麻烦。
我被告知要查看这个addProduct()方法,看看我如何编写所购买的(int quantityPurchased)方法。
以下是代码:
public void addProduct(String desc, int qty, double price) throws SQLException {
try (Connection conn = SimpleDataSource.getConnection()) {
try (PreparedStatement stat = conn.prepareStatement(
"INSERT INTO ProductsDB (Product_Code, Description, Quantity, Price) VALUES (?, ?, ?, ?)")) {
stat.setString(1, productCode);
stat.setString(2, desc);
stat.setInt(3, qty);
stat.setDouble(4, price);
stat.execute();
}
}
}
这就是我应该完成的事情:
/**
* Increases the quantity of product when we've purchased products to
* replenish our supply.
*
* @param number
* the count of products purchased.
* @throws SQLException
* - on any database error
*/
public void purchased(int qtyPurchased) throws SQLException {
// TODO: Update the ProductsDB table's quantity for this
// object's product code.
}
答案 0 :(得分:1)
首先,如果您要更新同一个表,则需要知道要更新数量的产品。在这方面,您需要在您购买的()方法中使用另一个参数,因此它将如下所示:
purchased(string productCode, int qtyPurchased)
。
在此之后,您需要编写另一个准备好的语句,该语句使用产品的新值更新该表。
看看这个:
//Added another parameter for the method that takes the product code.
public void purchased(string productCode, int qtyPurchased) throws SQLException
{
try (Connection conn = SimpleDataSource.getConnection())
{
//Updated prepared statement to update a product row instead of inserting a new one using the specified product code.
try (PreparedStatement stat = conn.prepareStatement("UPDATE ProductsDB SET Quantity = ? WHERE Product_Code = ?")
{
//Update the values used in the prepared statement
stat.setInt(1, qtyPurchased);
stat.setString(2, productCode);
//Execute the statement (important)
stat.execute();
}
}
}
进一步阅读:
https://www.mkyong.com/jdbc/jdbc-preparestatement-example-update-a-record/
答案 1 :(得分:0)
我发现这可以获得55
的{{1}}。
只需将其添加到上面的代码中:
qtyPurchased