0

im doing an inventory software, and i have a modify frame where you introduce an id and then you can select the fields that you are going to update, the fields are JtextField and you select them by checkBoxes. The software have spanish words, so if you don't understand what it means feel free to ask.

This is the frame

I have the preparedStatement code, but it updates all the fields. I don't know if there is a code to only do an update from checked fields.

 public static void modificar(int id,String nombre,String marca,String descripcion,String tamaño,String departamento,float precio) throws SQLException
        {
            Connection conn = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        String connectionUrl = "jdbc:mysql://localhost:3306/inventario";
        String connectionUser = "root";
        String connectionPassword = "root";
        conn = (Connection) DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
        String sqlStmt = "UPDATE Producto SET nombre=?, marca=?,descripcion=?,tamaño=?,departamento=?,precio=? WHERE idProducto='"+id+"'";
        prepStmt = conn.prepareStatement(sqlStmt);

                  if(!nombre.isEmpty()){
        prepStmt.setString(1, nombre);
                  }
                  if(!marca.isEmpty()){
        prepStmt.setString(2, marca);
                  }
                  if(!descripcion.isEmpty()){
                    prepStmt.setString(3, descripcion);
                  }
                  if(!nombre.isEmpty()){
                  prepStmt.setString(4, tamaño);
                  }
                  if(!departamento.isEmpty()){
        prepStmt.setString(5, departamento);
                  }
                  if(precio!=0){
                    prepStmt.setFloat(6, precio);
                  }
        prepStmt.executeUpdate();

    } catch (Exception e) {
        e.printStackTrace();
    } 

all i can think about is to write methods for every possible combination. I hope you can help me, Thanks.

Eduardo Moreno
  • 111
  • 2
  • 9
  • Possible duplicate of [Update columns if input values are not null otherwise ignore and keep the existing values of column in database](http://stackoverflow.com/questions/32018418/update-columns-if-input-values-are-not-null-otherwise-ignore-and-keep-the-existi) – Sam May 21 '17 at 02:19

1 Answers1

0

I don't know if there is a code to only do an update from checked fields.

You need to check the state of the checkbox, not the text field. Something like:

if (nombreCheckBox.isSelected())
    prepStmt.setString(1, nombre);
camickr
  • 321,443
  • 19
  • 166
  • 288