Send data to database

3

I'm studying for a Java test on database and I'm pretty confused, I was doing a program based on another, I made a sign-up screen and it works perfect, the only thing missing is send and I do not know how do this look the example and can not find.

Code Saving:

 Produtos t = new Produtos();

 try
 {
    t.setMarca(txtMarca.getText());

    t.setNome(txtNome.getText());
    t.setPreco(Float.parseFloat(txtPreco.getText()));
    t.setQuantia(Integer.parseInt(txtQuantidade.getText()));
    JOptionPane.showMessageDialog(this, "Sucesso a cadastrar", 
            "Sucesso" ,JOptionPane.INFORMATION_MESSAGE);       
    Limpar();
}
catch(Exception ex){
    JOptionPane.showMessageDialog(this, "Erro a cadastrar", 
            "Erro" ,JOptionPane.INFORMATION_MESSAGE);               
}

I have a save method but I do not understand it and if it is right or not

public void Salvar() throws SQLException
{ 
    try
    {
        conectaBanco conexao = new conectaBanco();
        String sql = ("insert into produtos (nome,marca,preco,quantia) values (?,?,?,?) ");
        try (PreparedStatement stmt = conexao.prepareStatement(sql)) {
           stmt.setString(1, nome);
           stmt.setString(2,marca);
           stmt.setFloat(3, preco);
           stmt.setInt(4, quantia);
           conexao.desconecta();
           stmt.execute();
        }
    }           
    catch(Exception ex)
    {
         System.out.println("Erro");
    }  
 }
    
asked by anonymous 21.11.2015 / 17:09

1 answer

0

Change the Save method to the form below, as it has a simple error where you are disconnected from the database before executing the insert on it:

public void Salvar() throws SQLException
{ 
    try
    {
        conectaBanco conexao = new conectaBanco();
        String sql = ("insert into produtos (nome,marca,preco,quantia) values (?,?,?,?) ");
        try (PreparedStatement stmt = conexao.prepareStatement(sql)) {
           stmt.setString(1, nome);
           stmt.setString(2,marca);
           stmt.setFloat(3, preco);
           stmt.setInt(4, quantia);
           stmt.execute();
           conexao.desconecta();
        } catch(Exception ex){
            System.out.println("Erro insert.");
        }// finally { //Ou você pode desconectar usando o finally do try
            //conexao.desconecta();
        //}

    }           
    catch(Exception ex)
    {
         System.out.println("Erro");
    }  
 }
    
21.11.2015 / 19:03