如何使用OOP概念为数据库赋值?

时间:2015-09-12 01:53:53

标签: java oop jdbc

我已经为食品订购系统创建了一个项目。但是我的讲座说你想要使用面向对象的编程概念,所以我想知道我是如何正确使用java类的。

这是我的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概念呢?

1 个答案:

答案 0 :(得分:0)

这是一个开始:

STDERR

Product pr = new Product(pId, pName, pCategory, price, qty, description); if (pr.insert()) { 类需要实例字段来表示产品的状态。 Product方法需要是实例方法(不是insert方法),并且需要写出static字段的状态。

由于这是一个教学练习,我将让你做其余的事。