Why is this Resultset returning null?

Asked

Viewed 305 times

5

If I run a query in the database returns result, however, when running java code, assigning the result to a Resultset, the same appears to be empty. You can 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>"});

                }
            }

2 answers

7

The method setString() already escapes and adicin 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);
  • That’s correct, now I’ve removed the apostrophes of both setString() and SQL command and it worked perfectly. Thank you!

  • 3

    @Marcoauréliosouza If this answer has solved your problem, click the green mark to mark the question as solved and to mark that this answer served to solve it.

  • All right, thank you!

1


Using a between Strings can cause many bugs, there are better ways to implement (using a like using wildcards for example).

Seeing the name of the field dates it seems to me wrong even, the attribute (in SQL) is type date then:

First perform a parse (using Simpledateformat) of the string for an object Date:
Note that I used Pattern "dd/MM/yyyy" you must apply your as the standard which 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 dates using the method 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()))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.