Problem with database insertion

1

I have the following code on my system:

    public int insert_dependente(Dependente dependente) {
    ResultSet r;
    int result = 0;
    if (!(dependente == null)) {
        try {
            Connection conn = new Conexao().getConnection();
            String sql = "insert into Dependente "
                    + "(IdAssoc,"
                    + "NomeDep,"
                    + "SobrenomeDep,"
                    + "RgDep,"
                    + "CpfDep,"
                    + " DtNascDep,"
                    + " emailDep,"
                    + " tipoDep,"
                    + " DtCriacaoDep)"
                    + " VALUES (" + dependente.getAssociado() + ","
                    + "'" + dependente.getNome() + "',"
                    + "'" + dependente.getSobrenome() + "',"
                    + "'" + dependente.getRg() + "',"
                    + "'" + dependente.getCpf() + "',"
                    //+ new java.sql.Date(dependente.getNascimento().getTime()).toString() + ","
                    + "'" + dependente.getEmail() + "',"
                    + "'" + dependente.getTipoDep() + "'";
                    //+ new java.sql.Date(new java.util.Date().getTime()).toString() + ")";
            Statement state; 
            state = conn.createStatement();
            state.execute(sql);
            state.close();

            String sql2 = "SELECT IdDep FROM Dependente WHERE CpfDep = " + dependente.getCpf();
            state = conn.createStatement();
            r = state.executeQuery(sql2);
            while (r.next()) {
                result = r.getInt("idDep");
            }
            r.close();
            state.close();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(DependenteDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return result;
}

My problem is that when the system arrives on the line

state.execute(sql);

The code does not run in my database, and then the system jumps straight to the line

return result;

I have tried everything but I can not find where my error is. Does anyone have an idea of what it can be?

    
asked by anonymous 18.05.2015 / 00:17

1 answer

2

Your code has several problems. The first of these is that when commenting the date fields in the first SQL, it became malformed. It expects 9 fields in INSERT , but you only get 7. In addition it was missing a date-parenthesis in SQL, since it was commented together with the last date.

Then, use PreparedStatement to avoid SQL Injection :

Third,use try-with-resources

18.05.2015 / 15:46