我已经创建了准备好的语句对象。 现在我想得到多个查询的结果。是否可以使用单个准备好的语句对象/找到下面的代码
PreparedStatement ps = null;
String moviedirectorQry = "SELECT movie_director FROM movies WHERE movie_title= ?";
ps = dbConnection.prepareStatement(moviedirectorQry);
ps.setString(1, "Twilight");
ResultSet rs=null;
rs = ps.executeQuery(moviedirectorQry);
while (rs.next()) {
String director_name = rs.getString("movie_director");
System.out.println("director name : " + director_name);
}
现在我想运行另一个查询..该怎么做
最佳答案
如果想法是对相同类型的不同查询使用相同的 PreparedStatement
且仅更改参数值,是的,这是可能的,只需调用 clearParameters()
在设置新参数值之前,请先清除参数,以防您想重复使用它。
代码可能是这样的:
if (ps == null) {
// The PreparedStatement has not yet been initialized so we create it
String moviedirectorQry = "SELECT movie_director FROM movies WHERE movie_title= ?";
ps = dbConnection.prepareStatement(moviedirectorQry);
} else {
// The PreparedStatement has already been initialized so we clear the parameters' value
ps.clearParameters();
}
ps.setString(1, someValue);
ResultSet rs = ps.executeQuery();
注意:您应该使用executeQuery()
而不是ps.executeQuery(moviedirectorQry)
,否则提供的参数值将被忽略这样查询就会失败。
关于java - 使用单个 PS 执行多个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41588851/