PreparedStatement does not check if it is Null Java

0

I'm doing a program that looks for a license plate in the database, and if it does not find it executes a sentence, and if there already exists the license plate that executes another one, but always (exists or not) executes the one that says not to be null I have tried the following code in the ActionPerformed of the button:

try {
            if(cn.BuscarMatricula(txt_Matricula.getText()).wasNull()){
                JOptionPane.showMessageDialog(this, jComboBox2.getSelectedItem());
                //cn.InsertarDatos(jComboBox2.getSelectedItem().toString(), txt_Modelo.getText(), txt_Matricula.getText(), txt_NIF.getText(),reparacion);
            }else{
                cn.actualizarMatricula(reparacion, Integer.parseInt(txt_ID.getText()));
                JOptionPane.showMessageDialog(this, "Actualizado correctamente");
            }
        } catch (SQLException ex) {
            Logger.getLogger(GestionVehiculos.class.getName()).log(Level.SEVERE, null, ex);
        }

And here I attach the method of actualizarMatricula :

public void actualizarMatricula(boolean enReparacion, int id){
        Connection cn = Conectar();
        Statement st;
        ResultSet rs = null;
        try{
            PreparedStatement pst = cn.prepareStatement("UPDATE vehiculos SET reparacion = ? WHERE id = ?");
            pst.setBoolean(1, enReparacion);
            pst.setInt(2, id);
            pst.executeUpdate();
        }catch(Exception e){
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, e);
        }
    }

searchCard:

public ResultSet BuscarMatricula(String matricula){
        Connection cn = Conectar();
        Statement st;
        ResultSet rs = null;
        try{
            PreparedStatement pst = cn.prepareStatement("SELECT * FROM vehiculos WHERE matricula = ?");
            pst.setString(1, matricula);
            rs = pst.executeQuery();
        }catch(Exception e){
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, e);
        }
        return rs;
    }

Any reason why it always enters the else, exists or not? I do not get the error, and the log shows that whatever I do tries to parse the ID that is in the else.

    
asked by Alberto Martínez 23.12.2018 в 00:20
source

3 answers

2

When I want to solve this type of situation this is what I do and it works very well for me.

public boolean validarRegistro(String Codigo) throws Exception {
                this.Conexion();
                ResultSet rs;
                try {
                    String sql = "select count(*) as cantidad from Tabla where CodCampo = ?";
                    PreparedStatement ps = this.getCn().prepareStatement(sql);
                    ps.setString(1, Codigo);
                    rs = ps.executeQuery();
                    int cantidad = 0;
                    if (rs.next()) {
                        cantidad = rs.getInt("cantidad");
                    }
                    return cantidad == 0;
                } catch (Exception e) {
                    throw e;
                }
            }

If the record does not exist it will return true , taking into account this we do the following.

try {

     if(validarRegistro(Codigo)){
          //Codigo que se ejecuta si NO EXISTE
     }else{
          //Codigo que se ejecuta si EXISTE
}
    
answered by 25.12.2018 / 01:48
source
1

I am editing my answer. If you do not want to modify anything in your Dao (look for Enrollment), you could also just modify a line of your front-end, like this:

if(cn.BuscarMatricula(txt_Matricula.getText()).next()){
        //lo que haces si encuentras la matrícula
}else{
        //lo que haces si NO encuentras la matrícula
}

I am changing the wasNull () to the .next (), which is a very common practice when obtaining your ResultSet. It is a common practice within the Dao itself. In fact if (rs.next ()) is used when the result you expect is only 1 record (or none) (which is your case); and while (rs.next ()) when you wait for several records

if(rs.next()){
    //y empiezo a obtener los datos de mi resultSet
    vehiculo.setNombreCampo(rs.getString("nombreCampo"));
}

As you can see this one if, you would already be using it in your front-end, in the Action-Performed

Greetings!

    
answered by 24.12.2018 в 19:08
0

From Javadoc :

  

Reports if the last column read had a value of SQL NULL. Note that you must first call one of the getter methods on a column to try to read its value and then call the method wasNull to see if the value read SQL NULL.

That is, you always get false because you have not tried to read the column (which makes sense if you take into account that there could be many columns in the same record, some null and another not, how would you decide then? wasNull ?)

In any case, the structure is bad; if you just want to get a value then BuscarMatricula should return that value, and not the ResultSet to lose it (or hiding the implementation details to the code that calls the method)

    
answered by 23.12.2018 в 09:52