Simplify java buttons Change + Save

0

I have an application with 6 buttons on each screen, save, change, new, delete, exit, cancel.

I would like help to put together two save and change buttons in one, to clean my screen a bit.

Make a single button that does both save and change, ie if the id (which is the primary key in the user table database) does not exist in the system create a new register (INSERT in the database), if it already exists change the register (UPDATE in the database), I need only the logic of database manipulation, the treatments I worry about later.

I found several topics on the internet but I still did not understand the logic. I use Postgres + Java. Thanks!

THIS IS THE ACTION WHICH THE CHANGE BUTTON MAKES IN MY USER REGISTRATION, BUT THAT FOLLOWS THE SAME LOGIC THAT I USE TO REGISTER COMPANIES AND EMPLOYEES

conecta.conexao();
try {            
        PreparedStatement pst = conecta.connection.prepareStatement("UPDATE USUARIO SET SENHA=?,NOME=? WHERE LOGIN=?");            
        pst.setString(1, jPFSenha.getText());
        pst.setString(2, jTNome.getText());
        pst.setString(3, jTLogin.getText());
        pst.executeUpdate();

        JOptionPane.showMessageDialog(null, "Dados alterados com Sucesso");

        preencherTabela("select * from USUARIO order by login");//executa o método de preencher os dados na jTable com as informações do banco de dados

    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, "erro ao alterar dados "+e);
    }
}

SAVE BUTTON

conecta.conexao();
if(!jTLogin.getText().equals("") && !jTNome.getText().equals("") && !(String.valueOf(jPFSenha.getPassword()).equals(""))){

        try {

            String SQL = "INSERT INTO usuario(login, senha, nome) VALUES(?,?,?)";


            try (PreparedStatement pst = conecta.connection.prepareStatement(SQL) 
            ) {
                pst.setString(2, String.valueOf(jPFSenha.getPassword()));
                pst.setString(3, jTNome.getText());
                pst.setString(1, jTLogin.getText());
                pst.execute(); 
            } 
            JOptionPane.showMessageDialog(null, "Dados CADASTRADOS com Sucesso");
            preencherTabela("select * from USUARIO order by login");//executa o método de preencher os dados na tabela com as informações do banco de dados
            limpar();//executa o método de limpar os dados do jTextField

        } catch (HeadlessException | SQLException e) {

            JOptionPane.showMessageDialog(null, "erro ao alterar dados "+e);
        }
        }else{
            JOptionPane.showMessageDialog(null, "Favor preencher o cadastro completo!!");         
    }

OBs: The two buttons are working perfectly just want a save button to do both save and change operations.

Follows my user registration screen.

When the client clicks on the table row the data appear in jTextField, then the program uses the jTextField data to change the data in the database, when the client clicks the new button, clears all jTextField data, and Click Save System saves a new record in the database, so I wanted the system to check if the database already exists in the database, it does an update and if there was no insert. I can not make it clearer that this, if any information is missing please let me know.

    
asked by anonymous 11.10.2017 / 12:17

1 answer

1

Douglas, with the structure that you now have the easiest is to make a function in the database that receives by parameter your login, name and password and the database "flips" with the data. Create a function:

CREATE FUNCTION upsert_usuario(loginParam TEXT, nomeParam TEXT, senhaParam) 
RETURNS VOID AS
$$
BEGIN
    LOOP
        -- tenta atualizar o registro
        UPDATE usuario SET nome = nomeParam, senha = senhaParam WHERE login=loginParam;
        IF found THEN
            RETURN;
        END IF;
        -- se não encontrou nenhum registro continua a execução do loop
        BEGIN
            INSERT INTO usuario(login, nome, senha) VALUES (loginParam, 
nomeParam, senhaParam);
            RETURN;
        END;
    END LOOP;
END;
$$
LANGUAGE plpgsql;

Just leave a button to call the function passing the parameters, to make the call put this sql

String sqlQuery = "SELECT upsert_usuario(?,?,?)";

In this way, executing the query, the database resolves to insert or update the data.

    
12.10.2017 / 20:04