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.