Simplify java buttons Change+Save

Asked

Viewed 825 times

1

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

I would like help to join two save and change buttons in one, to clear my screen a little.

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

I found several topics on the internet but still not intendi logic. Use Postgres + Java. Thank you!

THIS IS THE ACTION THAT THE CHANGE BUTTON DOES ON MY USER REGISTER, BUT IT 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!!");         
    }

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

Follow my user registration screen.

Segue a minha tela de cadastro de usuário.

When the client clicks on the table row the data appears in jTextField, then the program uses the jTextField data to change the data in the database, when the client clicks on the new button, clean all the data of jTextField and when clicking save the system writes a new registration in the database, so I wanted the system to make a check if the informed registration already existed in the database it would make an update and if it did not exist do an Insert. I can’t make it any clearer than that, in case any information is still missing please let me know.

  • Please access the link and add a [mcve] so that it is possible to analyze the problem better.

  • Sorry again, I’ve made the necessary edits, I think you can now understand what I need.

  • I still don’t see a [mcve]. You expect improvement tips but don’t present an executable code. Understand how it makes any hint difficult?

1 answer

1

Douglas, with the structure you have now the easiest is to make a Function in the database that receives by parameter your login, name and password and the database "turns" 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 make the Function call passing the parameters, to make the call put this sql

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

Thus executing the query the database resolves to insert or update the data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.