2016-10-10 2 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을 배울 –

+0

SQL UPDATE 문을 사용하여 다음 문제 – 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(); 
       } 
      } 
     } 

추가 읽기 : :이 qtyPurchased에 대한 55를 얻기 위해 작동하는지 발견

https://www.mkyong.com/jdbc/jdbc-preparestatement-example-update-a-record/

+0

이 작동하지만 구입 한 금액으로 수량을 바꿉니다. 구입 한 금액을 현재 수량에 추가해야합니다. 예를 들어, 현재 수량은 50이고, 5를 사고 싶기 때문에 55를 표시해야하지만, 단지 5를 표시합니다. – sparkles

+0

내 의견을 참조하십시오. – sparkles

+0

좋아,이 경우 내가 제공 한 것과 비슷한 작업을 수행해야합니다. 너 위. 차이점은 ProductCode를 사용하는 GetProductQuantity라는 새 메서드에 대해 하나의 매개 변수 만 갖게된다는 것입니다. "SELECT Quantity FROM ProductsDB"로 준비된 진술을 업데이트하면 지정된 제품의 총 금액을 알 수 있습니다. 이 후에는 구입 한 방법에 계산을 포함시켜야합니다. 나는 그렇지 않으면 너는 아무것도 배우지 않을 것이다 그것을 모두 기울인다. –

0

이에서보세요.

// 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/)이 일단이 질문에 더 많은 관심을 끌 수 있습니다. 평판). - [검토 중] (리뷰/저품절 포스트/13954836) –

+0

죄송합니다. 대답은 거기에 있습니다. – Luz1fer

관련 문제