How to add values to a detail without duplicating them


Good morning everyone I hope you can help me with this doubt I have a table in java where I load records from my table detail in sql server, as shown in the image.

The fields that the table has in the database are the same as those in the image, this data belongs to an order that has already been made, but it is still valid. What I want to do is that when adding another detail to the table and make the insert I only insert the new records and those that were already ignore them but until now I have not been able to do so I hope you can help me thanks for your time.

asked by OsGamez 21.11.2018 в 21:16

1 answer


With this first algorithm you can build the statement that would allow you to modify the value of interest in the database. One at a time.

public void actualizarBD(int id, String valor, int columna){
    String sentencia = "UPDATE zapateria.productos SET ";

    switch(columna){ // se concatena la sentencia de modificar la tabla con la columna de interes
        case 0:
            sentencia += "SUELA = '"+valor+"' ";
        case 1: 
            sentencia += "COLOR = '"+valor+"' ";
            // Agregar el resto de las columnas. Ignoradas por simplicidad

    // Se coloca la ultima parte de la sentencia
    sentencia += "WHERE id = "+id+";";

    System.out.println("sentencia : "+sentencia);

Subsequently a listener is added to the table specifically to the DefaultTableModel, which is the one that contains the data of the same, to know if there was any change and where it changed and what new value was added.

// Se agrega un evento que escuche cada vez que cambie un campo en la tabla grafica
    tabla.getModel().addTableModelListener(new TableModelListener() {
        public void tableChanged(TableModelEvent e) { // se obtiene la fila y columna del elemento que cambio
            int fila = e.getFirstRow();
            int columna = e.getColumn();
            String valor = (String) tabla.getModel().getValueAt(fila, columna); // se obtiene el valor que cambio

            System.out.println("fila: "+fila);
            System.out.println("columna: "+columna);
            System.out.println("valor: "+valor);

            new Conexion().actualizarBD(1, valor, columna); // se actualiza la base de datos por cada elemento que cambie
            // Se necesitaria una ventana de confirmacion


Any improvement you can add is valid as long as you get what you need and your doubts are solved.

answered by 21.11.2018 в 21:56