Why not insert in the database?

0

Why does not the following insertion code in the database work? The code arrives until Joption "has arrived!"

private void btnCadastroActionPerformed(java.awt.event.ActionEvent evt) {                                            
    String sql = "INSERT INTO tbl_cliente(id, nome, nascimento, cpf, sexo, endereco, numero, bairro, cidade,estado, data_entrada, preco_pagamento, datapagamento, mespago)VALUES (12, "+txtNome.getText()+", 1222-10-20, 12312, 123, 123, 123, 123, 123,23, 123, 123, 123, 123)";
    JOptionPane.showMessageDialog(null, "chegou?", "chegou?", JOptionPane.INFORMATION_MESSAGE);
    try {
        pst = conecta.prepareStatement(sql);;
        pst.executeQuery(sql);
        JOptionPane.showMessageDialog(null, "Cadastrado", "Cadastrado", JOptionPane.INFORMATION_MESSAGE);
    } catch (SQLException error) {
    }
}
    
asked by anonymous 04.06.2016 / 03:36

1 answer

0

It is failing because you are using the wrong method to execute the query (you should use executeUpdate() instead of executeQuery() ), and also because you are passing nome and nascimento to SQL instead of SQL values. That is, out of quotation marks. It would be better to use parameters in PreparedStatement , for example:

String sql = "INSERT INTO tbl_cliente " +
             "(id, nome, nascimento, cpf, sexo, endereco, numero, bairro, " +
             "cidade,estado, data_entrada, preco_pagamento, datapagamento, "+
             "mespago) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement pst = conecta.prepareStatement(sql);
pst.setInt(1, 12);
pst.setString(2, txtNome.getText());
pst.setString(3, "1222-10-20");
pst.setInt(4, 12312);
// ...
pst.executeUpdate();

More information about methods executeQuery() , executeUpdate() , setInt() , setString() , etc. is in the % s API .

If it makes sense in your program, you can set some parameters in the SQL code. But if it is of certain types, for example PreparedStatement , VARCHAR or DATE , it is necessary in quotation marks ( TIMESTAMP ):

String sql = "INSERT INTO tbl_cliente (id, nome, nascimento, cpf) " +
             "VALUES (5, 'Fulano', '1222-10-20', ?)";

But it's a bad idea to just try to add a string that comes from the user to your SQL code:

// XXX NAO FAÇA ISSO!
String sql = "INSERT INTO tbl_cliente (nome) VALUES ('"
           + txtNome.getText() + "')";

because it supports the possibility of SQL Injection . And in general it is neither accurate nor convenient because the ' method already exists in setString() .

    
04.06.2016 / 11:16