以下是我搜索特定字符串的方法:
(我想在书籍表的标题中搜索)
private static String searchInDB(String keyword) {
String url = "jdbc:mysql://localhost/bookstore";
String query = "Select title from books where title like %?% ";
try {
Connection connection = DriverManager.getConnection(...);
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, keyword);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
return rs.getString("title");
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
return null;
}
但是当我称这种方法时:
System.out.println(searchInDB("so"));
结果中有一个例外:
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which
is 0).
null
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
...
更新
我添加此代码以获取所有结果,但我进入了具有相同值的不定式循环!
String result = searchInDB("so");
while (result != null) {
System.out.println(result);
}
答案 0 :(得分:2)
更改代码,使通配符包含在参数中,而不是查询中,即:
String query = "Select title from books where title like ?";
....
ps.setString(1, "%" + keyword + "%");
修改重新提问,其他问题
AFAIK Java没有yield return功能,因此您需要更改方法签名。 目前,您将返回第一个结果,然后永远不会返回该函数。
我的Java非常基础,但是如何:
private static List<String> searchInDB(String keyword) {
List<String> theStrings = new List<String>();
String url = "jdbc:mysql://localhost/bookstore";
String query = "Select title from books where title like %?% ";
try {
Connection connection = DriverManager.getConnection(...);
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, keyword);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
theStrings.Add(rs.getString("title"));
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
return theStrings ;
}