MYSQL query from JAVA

1

Good I am trying to put data that are not of type String in my bd made in netbeans, I need a double and a int , but when putting them I get an error, things that do not happen if I do with a String , I leave here the fragment of my code that needs that:

if(codigo==null){
            JOptionPane.showMessageDialog(this,"SELECCIONA Y CARGA ANTES DE GUARDAR");
        }
        else{
        baseDatos bd= new baseDatos();
        Connection cn= bd.Conectar();
        //combersion de tipos
        double precio2= Double.parseDouble(precio.getText());
        Integer numdias2= Integer.parseInt(numdias.getText());

        try {
            PreparedStatement pps= cn.prepareStatement("UPDATE PRESTAMO SET "
                    + "PRECIO='"+precio2+"',"
                    + "NUMDIAS='"+numdias2+"'"
                    + "WHERE NUM_SOCIO= "+codigo);
            pps.executeUpdate();
        } catch (SQLException ex) {
            System.out.println("ERROR AL MODIFICAR ->"+ex);
        }
       bd.cierraConexion();
        cargar(-1);
        }
    }                                    
String codigo;

Sorry if it's too abstract

    
asked by Fausto Jeje 25.05.2018 в 23:13
source

2 answers

1

The problem is that you are trying to save the variables as strings . You have to remove the quotes like this:

try {
    PreparedStatement pps= cn.prepareStatement("UPDATE PRESTAMO SET "
            + "PRECIO="+precio2+","
            + "NUMDIAS="+numdias2
            + " WHERE NUM_SOCIO= "+codigo);
    pps.executeUpdate();
} catch (SQLException ex) {
    System.out.println("ERROR AL MODIFICAR ->"+ex);
}
    
answered by 25.05.2018 / 23:19
source
1

The PreparedStatement has a particular functionality, within this is that you can put a question mark "?" where the parameters that are going to be changing are going. And it also has specific methods for each type of field, int, String, even blobs, and objects.

In the case you mention, I would do it like this:

PreparedStatement pps=
  cn.prepareStatement("UPDATE PRESTAMO SET PRECIO=?, NUMDIAS=? WHERE NUM_SOCIO=?");

//ahora seteo los parámetros:
 pps.setDouble(1, precio2); //1 porque es el índice de al primera interrogación
 pps.setInt(2, numdias2); //2 porque es el....
 pps.setInt(3, codigo); ///ojo, asumo que código es int, sino cambia al tipo que sea.

After this, we execute:

 pps.executeUpdate();

It does not make sense to use a PreparedStatement without taking advantage of its methods. In any case use the Statement.

    
answered by 25.05.2018 в 23:34