Why is this ResultSet returning null?

5

If I run a query in the database returns result, however, when I run the code in java, assigning the result to a ResultSet, it appears to be empty. Can you help me?

PreparedStatement ps = conectar.con.prepareStatement("select colaborador.codigo as 'colabcod', nome,"
                    + " emprestimo.codigo as 'emprescod', idcolaborador, dataempres from emprestimo, colaborador where "
                    + "idcolaborador = colaborador.codigo and dataEmpres between ? and ?");
            ps.setString(1, "'" + datainicial + "'");
            ps.setString(2, "'" + datafinal + "'");
            ResultSet rs = ps.executeQuery();

            if (!rs.next()) {
                JOptionPane.showMessageDialog(null, "Não há resultados para essa pesquisa");
            }else{
                while (rs.next()) {

                model.addRow(new String[]{rs.getString("emprescod"), rs.getString("nome"),
                rs.getString("dataempres"), "<Não Definido>"});

                }
            }
    
asked by anonymous 12.07.2015 / 19:17

2 answers

1

Using a between strings can cause many bugs, there are better ways to implement

a> (using a like using wildcards for example).

Looking at the name of the field dataEmpres seems to me wrong, the attribute (in SQL) is type date then:

First parse (using SimpleDateFormat ) from the string to an object Date :
Note that I used the pattern "dd/MM/yyyy" you should apply yours as the default that is obtained from the variables datainicial and datafinal .

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date datai = formatter.parse(datainicial);
java.util.Date dataf = formatter.parse(datafinal);

Keep your PreparedStatement :

PreparedStatement ps = conectar.con.prepareStatement("select colaborador.codigo as 'colabcod', nome,"
                    + " emprestimo.codigo as 'emprescod', idcolaborador, dataempres from emprestimo, colaborador where "
                    + "idcolaborador = colaborador.codigo and dataEmpres between ? and ?");

Set the dates using the setDate sending a type java.sql.Date

ps.setDate(1, new java.sql.Date(datai.getTime()))
ps.setDate(2, new java.sql.Date(dataf.getTime()))
    
13.07.2015 / 00:48
7

The method setString () already escapes and adds quotes in the values, so it is not necessary to add quotes, they are the problem.

Your code should look like this:

ps.setString(1, datainicial);
ps.setString(2, datafinal);
    
12.07.2015 / 19:42