Invalid column index using PreparedStatement

巧了我就是萌 提交于 2019-12-02 14:24:33

问题


I am trying to query same data. But the preparedStatement thrown an SQLException about wrong indexing even though the index start from 1 as the documentation said.

Here is the function:

public List<Paper1> search(String keyword) throws NotConnectedException {

    List<Paper1> papers = new ArrayList<>();

    try {
        PreparedStatement searchKeyword = 
        connection.prepareStatement("SELECT title, registered FROM paper "
        + "WHERE title LIKE '%?%'");
        searchKeyword.setString(1, keyword);
        ResultSet rs = searchKeyword.executeQuery();

        while (rs.next()) {
            Paper1 p = new Paper1();
            p.setTitle(rs.getString("title"));
            p.setRegistered(rs.getDate("registered").toLocalDate());
            papers.add(p);
        }
        return papers;
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

The SQLException said, the wrong line is the

searchKeyword.setString(1, keyword);

because of the wrong column index


回答1:


Your question-mark place holder is inside single quotes, so it's being seen as a literal character - and not a place holder at all. When the statement is parsed the '%?%' is just a string and no bind variable is seen, so no bind variable can be set - there are no variables, so no variable with index 1.

You can use concatenation to fix this:

    PreparedStatement searchKeyword = 
    connection.prepareStatement("SELECT title, registered FROM paper "
    + "WHERE title LIKE '%' || ? || '%'");



回答2:


Print out the query string before executing it:

SELECT title, registered FROM paperWHERE title LIKE '%?%'

The answer should be obvious.

You need spaces to delimit keywords.



来源:https://stackoverflow.com/questions/43051975/invalid-column-index-using-preparedstatement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!