3

I've been trying to select data using preparedStatement and passing these arguments but an Exception happens.

Could anyone help me? Here is my code.

Connection connection = DBConnection.getConnection();
    String query = "select * from integrantes where nome like '?' or rm like '?'";
            ArrayList<Integrante> list = new ArrayList<>();
            try {
                PreparedStatement preparedStatement = connection.prepareStatement(query);
                preparedStatement.setString(1, ('%' + term + '%'));
                preparedStatement.setString(2, ('%' + term + '%'));
                JOptionPane.showMessageDialog(null, ((OraclePreparedStatement) preparedStatement).getOriginalSql());
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    list.add(new Integrante(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3), resultSet.getInt(4)));
                }
            } catch(SQLException e) {
                JOptionPane.showMessageDialog(null, "Erro ao listar o(s) integrante(s)." + e);
            } catch(NullPointerException e) {
                JOptionPane.showMessageDialog(null, "Ocorreu um erro inesperado.");
            } catch(Exception e) {
                JOptionPane.showMessageDialog(null, "Ocorreu um erro no código.");
            }

            return list;
3
  • select * is a poor way to structure a SQL statement rather than listing the columns. I would guess that your query does not return 4 columns but it's impossible to know. Commented Oct 16, 2016 at 6:07
  • select id_integrante, nome, rm id_grupo from integrantes; it works as well when I execute in Oracle SQL Developer Commented Oct 16, 2016 at 6:12
  • That is 3 columns not 4 (id_grupon is an alias for the rm column). Commented Oct 16, 2016 at 6:14

1 Answer 1

4

When using a PreparedStatement you must NOT put quotes around placeholders that are going to be substituted with strings. Your statement

"select * from integrantes where nome like '?' or rm like '?'"

causes the question marks to be treated as literals, so the statement has ZERO parameters, thus resulting in the exception. Change it to

"select * from integrantes where nome like ? or rm like ?"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.