Method to insert into the database is not pulling value [JAVA]

Asked

Viewed 87 times

0

Good night!

I’m trying to do a college job (JAVA), and I have to insert the client data into the database (Mysql), I have a Client class, a form, and the database class.

Form calling method for insertion (I changed some to not get polluted)

private void btIncluirActionPerformed(java.awt.event.ActionEvent evt) {
cliente.setNome(txtNome.getText());

    try {
        vServCadCliente.insertNome();
        //JOptionPane.showMessageDialog(null, "Inserido com sucesso");
        limpaTela();
        } catch (SQLException ex) {
            Logger.getLogger(frmCadCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
}    

Seat class (insertion method)

public void insertNome()throws SQLException{

        JOptionPane.showMessageDialog(null,"Achou");

        String sql = "insert into NOME(NOME)" +
        "values (?)";
        PreparedStatement ps;
        ps = conexao.getConexao().prepareStatement(sql);
        ps.setString(1, cliente.getNome());
        //usar sempre pra inserir ou modificar dado na tabela
        //JOptionPane.showMessageDialog(null,"Achou 2");
        ps.executeUpdate();
        JOptionPane.showMessageDialog(null,"Achou 2");
        ps.close();
        conexao.close();
    }

We debug, and the form is setting the value of the variable, but when we go to the database class method, it looks for ps.setString(1, .getName() as NULL, it is not pulling from the client class.

  • 1

    the method insertNome() should not receive the client as a parameter?

  • In this case, I should put the client object as a parameter?

1 answer

0


The problem is that you are most likely picking up the wrong client object and there are also other things to improve on the architecture of your project so come on.

First this guy here "vServCadCliente", briefly this guy gives me to understand that you created a class for each functionality of your crud (Registration, update, search...) to improve this you could create a responsible class only to administer these features to the Client object, something like:

Clientedao to be composed by the methods

  • public Boolean inserirCliente(Client)
  • public Boolean updateClient(Client)
  • public Boolean removerCliente(int codCliente)
  • public Arraylist searchClients()

Note: Instead of creating a method to update and another to insert you can create a method that already does both, like:

int upsertCliente(Cliente cliente) {
  //Se o cliente não tem código é porque ele não foi cadastro no banco 
  if(cliente.getCdCliente() == null) {
    //código para cadastrar
  } else {
    //código para atualizar
  }
}

Obs2: In the insertion, removal and update methods it is interesting that you put something that says whether or not the method was able to perform its role, so I put a Boolean as return(true if no error occurred during the operation or false if it occurred)because then you can show the user messages like "Customer Successfully Registered", "Unexpected Error" etc... In the case of upsert the return is an int, because in this way you can return 0 for errors, 1 for successful registration, and 2 for successful updates, the ideal would be to create something like an Enum for this but I’ve gone too long on this remark.

Now with the done Customer just create an object of it and call the method you will use, would be more or less like this:

 private ClienteDAO clienteDAO;

 //Construtor da sua Tela
 FormularioCliente() {
   clienteDAO = new ClienteDAO();
 }

 private void btnSalvarCliente(java.awt.event.ActionEvent evt) {

   Cliente novoCliente = new Cliente();
   novoCliente.setNome(txtNome.getText());
   novoCliente.setCpf(txtCpf.getText());        
   novoCliente.setTelefone(txtTelefone.getText());
   novoCliente.setEmail(txtEmail.getText());

  if(clienteDAO.inserirCliente(novoCliente)) {
    JOptionPane.showMessageDialog(null, "Cliente cadastrado com sucesso");
    limpaTela();
  } else {
    JOptionPane.showMessageDialog(null, "Ocorreu um erro inesperado, não for possível cadastrar o cliente");
  }

}

Your Class Clientedao

public boolean inserirCliente(Cliente cliente){
    String sql = "INSERT INTO cliente(nome,cpf,email,telefone) VALUES(?,?,?,?)";
    try { 
    PreparedStatement ps = conexao.getConexao().prepareStatement(sql);
        ps.setString(1, cliente.getNome());
        ps.setString(2, cliente.getCpf());
        ps.setString(3, cliente.getEmail());
        ps.setString(4, cliente.getTelefone());
        ps.execute();
        ps.close();
        //Consegui inserir
        return true;
    } 
    catch (SQLException u) { 
        //Não consegui inserir
        throw new RuntimeException(u);
        return false;
    } 

} 

Last Note: I have not tested anything of the code and also do not know how the other things are in your project, but the important thing here is the idea, which in short is to create a Clientedao class that will organize and describe ALL the interactions that your Client class will perform with the database.

Browser other questions tagged

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