2016-10-10 76 views
-1

我在数据库中增加购买产品的数量时有点麻烦。数据库中更新条目总数

有人告诉我看看这个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. 

} 
+3

使用SQL UPDATE语句 –

+0

学习一些SQL,然后尝试解决问题 – Blip

+0

的addProduct命令()方法基本上是给你你的答案... –

回答

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/

+0

这个工作,但它只是将数量替换为购买金额,我需要它将购买的金额添加到当前数量。例如,当前数量是50,我想购买5,所以它应该显示55,但它只显示5. – sparkles

+0

请看我的评论 – sparkles

+0

好吧,在这种情况下,你需要做一些类似于我给的东西你在上面。不同之处在于,对于名为GetProductQuantity的新方法,只有一个参数需要productCode。之后,将准备好的语句更新为“SELECT Quantity FROM ProductsDB”,这将为您提供指定产品的总金额。在此之后,您只需在您购买的方法中包含计算。我无法做到这一切,否则你不会学到任何东西。 –

0

我发现,这个工程得到55qtyPurchased。 只需添加这上面的代码:

// Just add the + getQuantity() and you're good to go. 
stat.setInt(1, qtyPurchased + getQuantity()); 
+0

这并没有真正回答这个问题。如果您有不同的问题,可以通过单击[提问](http://stackoverflow.com/questions/ask)来提问。您还可以[添加赏金](http://stackoverflow.com/help/privileges/set-bounties)在您拥有足够的[声誉](http://stackoverflow.com/help/)时吸引更多人关注此问题什么声誉)。 - [来自评论](/ review/low-quality-posts/13954836) –

+0

对不起,阅读我上面更新的评论回复帖子^。答案就在那里。 – Luz1fer