The data is not deleted from the database

0

I can not get my Java application to delete data from a database.

I attach code to my method to erase:

int rowIndex = this.tabla.getSelectedRow();

    try{
       String dni = String.valueOf( tabla.getValueAt(rowIndex, 0));
       st = con.createStatement(); 
       int fila = tabla.getSelectedRow();
       int col = tabla.getSelectedColumn();
       System.out.println(fila);
       System.out.println(col);
       String sql = "DELETE FROM clientes where dni="+dni;          

       st.executeUpdate(sql);
       modelo.removeRow(fila);

           JOptionPane.showMessageDialog(null, "Datos Borrados");

    }catch(SQLException e){
        JOptionPane.showMessageDialog(null, "Error al borrar");
    }

that code is called from a button in its actionListener . I've tried prepareStatement , and neither. I'm not interested in this form, since I do not know how to pass the DNI from a JTable as a parameter to the method.

    
asked by scorpions 02.06.2017 в 11:07
source

2 answers

2

I think the problem is the DNI string, you should put it in single quotes

 String sql = "DELETE FROM clientes where dni='"+dni+"'";       
    
answered by 02.06.2017 / 11:19
source
2

Even though there is already an admitted answer as correct, I consider that it includes a bad practice, so I add another one.

You should use PreparedStament and not concatenate the input parameters to avoid possible sql injection attacks.

Thus, the code would be:

try (PreparedStatement st=con.prepareStatement("DELETE FROM clientes where dni=?")){
    st.setString(1,dni);
    st.executeUpdate();
}catch(SQLException e){
    JOptionPane.showMessageDialog(null, "Error al borrar");
}
    
answered by 02.06.2017 в 12:28