java.sql.SQLException:列索引无效

时间:2016-10-16 06:05:05

标签: java sql oracle jdbc prepared-statement

我一直在尝试使用preparedStatement选择数据并传递这些参数,但会发生异常。

有人能帮帮我吗?这是我的代码。

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;

1 个答案:

答案 0 :(得分:2)

使用PreparedStatement时,不得在可替换字符串的占位符周围加上引号。你的陈述

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

导致问号被视为文字,因此该语句具有ZERO参数,从而导致异常。将其更改为

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