Java: get quantity of a product from the Database

0

I am learning on my own to do a management program for the sale of beverages.

I have a table called VENTAS_HOY that stores what products were sold, as well as their quantity.

It works for me, until it reaches the point of entering the table some product that is already. For example, I want to enter 5 Coca Colas, and in the table there are 2 for example. What I do not achieve is to do by some method, that I return the number 2 that is already in the table, to operate with it, and then update.

The table has 3 fields: Product, Quantity, Price. (The Beverages class has a constructor, among others, that accepts these 3 parameters for instantiation).

I currently have something like that ... But it does not work, or I can not understand it, it always returns 0. (Since I know that the product is already in the table and has a certain amount).

Can someone help me how to get this method to return an INT with the quantity of a product in the SALES_HOY table?

public int cantidadVenta (Bebidas vo){
 int cantidadVenta = vo.getCantidadCarrito();

 DBCon conec = new DBCon();
    String sql = "SELECT COUNT(cantidad) FROM VENTAS_HOY WHERE producto = ? ";
    PreparedStatement ps = null;
     try {
            ps = conec.Connect().prepareStatement(sql);
            ps.setInt(1, vo.getCantidadCarrito());
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
            cantidadVenta=rs.getInt(1);
            }
            /*
            if (rs!= null ){                
        Object[] fields = (Object[]) rs.getObject(0); 
        cantidadVenta = Integer.parseInt((String) fields[0]);
        System.out.println("DAO variable CantidadVenta en VENTAS HOY es: "+cantidadVenta);
    }
            */


        } catch(SQLException e) {
            Logger.getLogger(DAO.class.getName())
                    .log(Level.SEVERE, "Error en consulta", e);
        }

 System.out.println("DAO variable CantidadVenta en VENTAS HOY es: "+cantidadVenta);
 return cantidadVenta;
}
    
asked by Gabriel Mc Gann 14.03.2018 в 03:03
source

1 answer

1

The defined statement expects to be informed by the unique identifier of a particular product

SELECT COUNT(cantidad) FROM VENTAS_HOY WHERE producto = ?

However, when preparing the parameters with the following instruction, the product identifier is not being reported but another data vo.getCantidadCarrito ()

ps.setInt(1, vo.getCantidadCarrito());

You must replace this parameter with the correct one, in the code it is not clear if you already have the product identifier in the vo object, but assuming that, then the instruction should look something like this:

ps.setInt(1, vo.getIdProducto());
    
answered by 14.03.2018 в 11:11