public ArrayList<Message> searchMessages(String word) throws DaoException{
ArrayList<Message> messages = new ArrayList<>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = getConnection();
//String query = "SELECT * FROM messages WHERE text LIKE %?% order by date";
String query = "SELECT * FROM messages WHERE text LIKE '%?%'";
ps = con.prepareStatement(query);
ps.setString(1,word);
rs = ps.executeQuery();
while (rs.next()) {
int messageId = rs.getInt("messageId");
String text = rs.getString("text");
String date = rs.getString("date");
int memberId2 = rs.getInt("memberId");
Message m = new Message(messageId,text,date,memberId2);
messages.add(m);
//Company c = new Company(companyId, symbol, companyName, sharePrice, high, low);
//companies.add(c);
}
} catch (SQLException e) {
throw new DaoException("searchMessages(): " + e.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (con != null) {
freeConnection(con);
}
} catch (SQLException e) {
throw new DaoException("searchMessages(): " + e.getMessage());
}
}
return messages;
}
先解释一下代码。它只是简单地搜索消息表及其文本字段以查找提供的内容。我使用准备好的语句将其插入查询并运行它。无论我提供什么字符串给出这个错误
oow_package.DaoException: searchMessages(): Parameter index out of range (1 > number of parameters, which is 0).
完全不知道为什么它不起作用。非常感谢任何帮助。
最佳答案
您不能在准备好的语句中使用这样的参数。查询应该是
SELECT * FROM messages WHERE text LIKE ?
你应该使用
ps.setString(1, "%" + word + "%");
关于java - 使用java注入(inject)sql查询时,出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13019838/