samedi 31 octobre 2015

Insert a product and update its column

I have a table INVENTORY with 2 columns [product(primary key) - quantity]. I want to insert to this table a product with its quantity.

public boolean insertPackage(String product, int quantity) 
            throws SQLException, ClassNotFoundException {

        System.out.println("Insert product to Invetory");
        boolean flag=false;
        sq = "INSERT INTO INVENTORY VALUES (?, ?)";

        try {       
            Class.forName(typeDB);
            c = DriverManager.getConnection(path);            
            stm = c.prepareStatement(sq);

            PreparedStatement stm = c.prepareStatement(sq);

            stm.setString(1, product);
            stm.setInt(2, quantity);
            int rowsAffected = stm.executeUpdate();

        } catch (SQLException e) { 
            //There is already a same product in the Inventory
            flag = true;
            System.out.println(e.getMessage());
        } finally {
        if (stm != null)
                    stm.close();
        if (c != null)
                    c.close();
        }     

        return flag; //if the flag is true, then execute insert.
    }

If it returns true, then I search for this product, retrieve the quantity and then update the table with the new quantity. I am wondering if this way I thought, is a good way to check how to perform the insertion or there is a better one.

Aucun commentaire:

Enregistrer un commentaire