2015-09-12 36 views
0

我已經爲食品訂購系統創建了一個項目。但我的講座說你想爲此使用面向對象的編程概念,所以我想知道我是如何正確使用java類的。如何使用OOP概念將值壓縮到數據庫?

這裏是我的GUI代碼:

//get values from user 
     int pId = Integer.parseInt(txtProductID.getText()); 
     String pName = txtPName.getText(); 
     String pCategory = combCategory.getSelectedItem().toString(); 
     Double price = Double.parseDouble(txtPrice.getText()); 
     Double qty = Double.parseDouble(combQty.getSelectedItem().toString()); 
     String description = txtDescription.getText(); 

     Product pr = new Product(); 

     if(pr.insertProduct(pId, pName, pCategory, price,qty,description)){ 

      JOptionPane.showMessageDialog(null, "Successly Added to DataBase!!"); 
     }else{ 
      JOptionPane.showMessageDialog(null, "UnsucessFully"); 

     } 

這裏是我的產品類別

//insert to product into database 
    public static boolean insertProduct (int id,String name,String category,Double price,Double qty,String description){ 
      boolean flag = false; 
     try {    
      DBconnector db = new DBconnector(); 
      con = db.connect();    
      String s="insert into product(id,name,category,price,qty,description) VALUES (?,?,?,?,?,?)"; 

     PreparedStatement preparedStatement = con.prepareStatement(s); 
      preparedStatement.setInt(1, id); 
      preparedStatement.setString(2, name); 
         preparedStatement.setString(3, category); 
         preparedStatement.setDouble(4, price); 
         preparedStatement.setDouble(5, qty); 
         preparedStatement.setString(6, description); 

         if(preparedStatement.executeUpdate()>0) 
          flag = true; 

     }catch (SQLException ex){ 
      ex.printStackTrace(); 
     } 

     return flag; 
    } 

那麼,如何做到這一點使用OOP概念?

+0

創建一個'Product'類,它攜帶您正在建模的屬性,在與您的數據層進行交互時使用此類(傳入並返回'Product')。我甚至可以考慮有一個'Product'管理器類,它可以完成你需要的基本操作(添加/插入,更新,刪除,查詢) – MadProgrammer

+0

非常感謝MadProgrammer –

回答

0

這裏是一個開始:

Product pr = new Product(pId, pName, pCategory, price, qty, description); 

    if (pr.insert()) { 

Product類需要實例字段來表示產品的狀態。方法insert需要是一個實例方法(而不是一個static方法),它需要寫入this的字段的狀態。

由於這是一個教學練習,我會讓你去做其餘的事情。

+0

非常感謝Stephen :) –

+0

將數據庫交互從產品像MadProgrammer建議的那樣。 – reaanb

+0

是的,也許。這取決於你需要多麼複雜。處理產品細節作爲實例字段可能是老師想要的第一個瞬間。 –