0

Quiero realizar una pregunta un podo difícil de formular, disculparme por anticipado. Cuando voy a realizar el PreparedStatement compruebo si la variable es NULL o está vacía con el método textoNoNULL(), si el texto está vació, como es el caso de la variable IBAN quiero que omita la acción, pero como en la sentencia está esperando un valor "iban = ?" me salta un error, me gustaría poder realizar dicha acción sin que de error, que envié un valor que no borre lo que contiene la Base de Datos por un campo vació o un NULL.

public void actualizarCuentaBancaria(){

      private String iban = "";
      private String entidad = 9012;
      private String sucursal= 0415;

            try {                
                    String sentencia = "UPDATE cuenta_bancaria SET iban= ?, entidad= ?, sucursal= ? WHERE id_persona = ?";

                    PreparedStatement pst = getConnection().prepareStatement(sentencia);                    


                    if(textoNoNULL(iban)) pst.setString(1, iban); else //AQUI
                    if(textoNoNULL(entidad)) pst.setString(2, entidad);
                    if(textoNoNULL(sucursal)) pst.setString(3, sucursal);

                    pst.setInt(6, idPersona);

                    pst.executeUpdate();
                    pst.close();
                } catch (SQLException ex) {

                } 
}

private boolean textoNoNULL(String palabra){
        if(palabra == null || palabra.length() == 0)
            return false;
        else 
            return true;    
}

2 respuestas 2

2

Si solo el iban puede ser null asi te bastaria:

if(textoNoNULL(iban)
       sentencia = "UPDATE cuenta_bancaria SET iban= ?, entidad= ?, sucursal= ? WHERE id_persona = ?";
else
       sentencia = "UPDATE cuenta_bancaria SET entidad= ?, sucursal= ? WHERE id_persona = ?";
                    PreparedStatement pst = getConnection().prepareStatement(sentencia);                    

                    int i=1;
                    if(textoNoNULL(iban)) {pst.setString(i, iban); i++;} //AQUI
                    if(textoNoNULL(entidad)) pst.setString(i, entidad); i++;
                    if(textoNoNULL(sucursal)) pst.setString(i, sucursal); i++;
                    pst.setInt(i, idPersona);

                    pst.executeUpdate();
                    pst.close();

Si los otros campos también pueden ser null deberías construirte la sentencia concatenando textos dependiendo si son nulos o no, una solución seria algo así:

    sentencia="UPDATE cuenta_bancaria SET ";
    boolean comapendiente=false;
    if(textoNoNULL(iban) 
         {sentencia+="iban=? ";
          comapendiente=true;
         }
    if(textoNoNULL(entidad) 
          {if(comapendiente) sentencia+=",";
         sentencia+="entidad=? ";
          comapendiente=true;
         }
    if(textoNoNULL(sucursal) 
          {if(comapendiente) sentencia+=",";
         sentencia+="sucursal=? ";
         }
    sentencia+="WHERE id_persona = ?";
 int i=1;
                    if(textoNoNULL(iban)) {pst.setString(i, iban); i++;} //AQUI
                    if(textoNoNULL(entidad)) pst.setString(i, entidad); i++;
                    if(textoNoNULL(sucursal)) pst.setString(i, sucursal); i++;
                    pst.setInt(i, idPersona);

                    pst.executeUpdate();
                    pst.close();
3
  • No me sirve, porque puede ser para cualquier Variable, he puesto un ejemplo de 3 campos, pero el que tengo que hacer tiene 30 campos. Gracias de todos modos.
    – Arkhan6
    el 2 ene. 2017 a las 11:01
  • Te actualice la respuesta
    – ReyJuanjo
    el 2 ene. 2017 a las 11:09
  • Me ha servido mucho, muchas gracias, he dejado una solución alternativa
    – Arkhan6
    el 2 ene. 2017 a las 12:47
-1

He mejorado la solución, he suprimido la variable "comapendiente" por un subString que borra el último caracter del String, es decir elimina la "coma".

public void actualizarCuentaBancaria(){
        try {  
                String sentencia = "UPDATE cuenta_bancaria SET ";

                if(textoNoNULL(iban)){
                    sentencia += " iban = ?,";
                }
                if(textoNoNULL(entidad)){
                    sentencia += " entidad= ?,";
                }
                if(textoNoNULL(sucursal)){
                    sentencia += " sucursal= ?,";
                }

                //Elimina la "coma" 
                sentencia = sentencia.substring(0, sentencia.length()-1); 

                sentencia +=" WHERE id_persona = ? ";

                int i = 1;

                PreparedStatement pst = getConnection().prepareStatement(sentencia);                                 

                if(textoNoNULL(iban)){ pst.setString(i, iban);  i++; }
                if(textoNoNULL(entidad)){ pst.setString(i, entidad);  i++; }
                if(textoNoNULL(sucursal)){ pst.setString(i, sucursal);   i++; }              

                pst.setInt(i, idPersona);

                pst.executeUpdate();
                pst.close();
            } catch (SQLException ex) {

            }
    }

private boolean textoNoNULL(String palabra){
        if(palabra == null || palabra.length() == 0)
            return false;
        else 
            return true;
}
1
  • Me alegro arkham, yo te puse un ejemplo rápido para que vieses la forma de hacerlo, un saludo y acepta la respuesta si te sirvio.
    – ReyJuanjo
    el 2 ene. 2017 a las 13:06

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.