Processing SQL statements with JDBC

3

I'm trying to use JDBC, but having difficulties with proper language use. I would like to pass the sql code down to java, and I need help with SELECT.

Regarding the variables sql1, sql2, sql3 and the use of their respective where ... (for me they are wrong). I did it this way having the clear impression that it was wrong, but I put it there to show what I wanted with my code.

select * 
from voo, voo_comissarios 
where voo.voo_id=voo_comissarios.voo_id and 
voo_comissarios.com_cpf=580069359 and 
voo.voo_data between '1000-1-1' and '2019-1-1';

static ResultSet vooComissario() {
        ResultSet res = null;
        String sql = "SELECT * FROM voo",
               sql1 = sql+  "WHERE voo.voo_data > ?"
               sql2 = sql1+ "WHERE voo.voo_data < ?"
               sql3 = sql2+ "WHERE voo.voo_id=voo_comissarios.voo_id";
               sql4 = sql3+ "WHERE voo_comissarios.com_cpf= ?"

        Connect();
        try {
            PreparedStatement stm;
                stm = con.prepareStatement(sql4);
                stm.setInt(1, serial);
                res = stm.executeQuery();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível recuperar os dados", "Erro", JOptionPane.OK_OPTION);
        }
        CloseConnection();
        return res;
    }
}
    
asked by anonymous 19.11.2016 / 01:00

1 answer

5

You did not explain the problem correctly, but from what you could understand, if it is to adapt the query within the method, I think it should look like this:

static ResultSet vooComissario() {
        ResultSet res = null;
        String sql = "select * from voo, voo_comissarios " +
                      "where voo.voo_id = voo_comissarios.voo_id and " + 
                      "voo_comissarios.com_cpf = ? and " +
                      "voo.voo_data between ? and ?";

        Connect();
        try {
                PreparedStatement stm = con.prepareStatement(sql);;

                //se for usar números em cpf, 
                //utilize o tipo LONG no lugar de INT
                stm.setLong(1 , variavelCpf);
                //passe as datas no formato java.sql.Date
                setm.setDate(2, dataInicial);
                setm.setDate(3, dataFinal);

                res = stm.executeQuery();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível recuperar os dados", "Erro", JOptionPane.OK_OPTION);
        }
        CloseConnection();
        return res;
    }
}
    
19.11.2016 / 01:46