Select in java MySQL

3

I do a function to verify if a plate exists in a table: 0 if it does not exist and 1 if it was found.

However, I do not understand why I still know that there is, when I only have one record in the table

public int buscarplaca(String placa){
    int enco=0;
    Connection cn = sql.Conectar();
    ResultSet rs=null;
    System.out.println(enco);
    String query= "select * from cliente_mensual where placa = '"+placa+"'"; 
    try {
        System.out.println(enco);
        rs = sql.stmt.executeQuery(query);
        rs.first();
        if(rs!=null){
                enco=1;
                System.out.println(enco);
        }
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null,ex);
        System.out.println(enco);
        return enco;
    }
    System.out.println(enco);
    return enco;
}

I enter a data that is not, but also returns 1.

The System.Out.Println are to verify what happens with enco .

    
asked by Daylight Ark 20.12.2016 в 01:55
source

2 answers

0

The database is consulted by a plaque. That result is saved in a ResultSet class. That class is no longer null, so it will always enter as stated. My solution is to have an accountant and if he does the tour it is because the value exists. Otherwise it does not exist.

Probably adding this code after the execution of the query:

rs = sql.stmt.executeQuery(query);

int count = 0;

while (rs.next()) {
    ++count;
    // Obtener datos de la fila actual y usarlos..
    // recorre hasta encontrar el valor o lo que quieras hacer.
}

if (count == 0) {
    System.out.println("No se encontro un registro");
}
    
answered by 20.12.2016 / 02:04
source
2

As the query has not found any record the resultset is not completely empty enough to compare it with a null . what you really should do the following:

 public int buscarplaca(String placa) {
        int enco = 0;
        Connection cn = sql.Conectar();
        ResultSet rs = null;
        System.out.println(enco);
        String query = "select * from cliente_mensual where placa = '" + placa + "'";
        try {
            System.out.println(enco);
            rs = sql.stmt.executeQuery(query);      
            if (!rs.next()) {
                 //ResultSet esta vacio
            } else {
                enco = 1;
                System.out.println(enco);
            }

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex);
            System.out.println(enco);
            return enco;
        }
        System.out.println(enco);
        return enco;
    }
    
answered by 20.12.2016 в 02:18