问题
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