Java 更新数据库中的项目总数
在数据库中增加产品购买时的数量时,我遇到了一些问题 我被告知查看这个addProduct()方法,看看如何编写purchased(int quantityPurchased)方法 这是代码:Java 更新数据库中的项目总数,java,database,jdbc,Java,Database,Jdbc,在数据库中增加产品购买时的数量时,我遇到了一些问题 我被告知查看这个addProduct()方法,看看如何编写purchased(int quantityPurchased)方法 这是代码: public void addProduct(String desc, int qty, double price) throws SQLException { try (Connection conn = SimpleDataSource.getConnection()) { tr
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.
}
首先,如果要更新同一个表,则需要知道要更新数量的产品。在这方面,您需要在purchased()方法中使用另一个参数,以便如下所示:
已购买(字符串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();
}
}
}
在此进一步阅读:
我发现这可以获得
qtyPurchased
的55
。
只需将此添加到上面的代码中:
// Just add the + getQuantity() and you're good to go.
stat.setInt(1, qtyPurchased + getQuantity());
使用SQL UPDATE语句了解一些SQL,然后尝试解决问题AddProduct()方法基本上会给出答案…^继续that@sparkles请看我的答案。这是有效的,但是它只是将数量替换为购买的数量,我需要它将购买的数量添加到当前数量。例如,当前数量是50,我想购买5,所以它应该显示55,但它只显示5。请查看我的评论好的,在这种情况下,您将需要执行类似于我上面给您的操作。不同之处在于,对于采用productCode的名为GetProductQuantity的新方法,只有一个参数。之后,将准备好的语句更新为“从ProductsDB中选择数量”,这将获得指定产品的总金额。在此之后,您只需在购买的方法中包含计算。我不能做这一切,否则你什么也学不到。这并不能真正回答问题。如果您有不同的问题,可以单击以提问。一旦你有足够的时间,你也可以吸引更多的注意力抱歉阅读我更新的评论回复帖子^。答案就在那里。