我正在尝试使用Prepared Statement来处理查询。问题是我有几个if if语句根据用户输入更改查询。
这是我的代码
if( !star_firstName.isEmpty() || !star_lastName.isEmpty() ){
baseQuery = "select m.id, title, year, director, banner_url, trailer_url from movies m, stars s, stars_in_movies sim WHERE m.id=sim.movie_id AND s.id=sim.star_id";
}
if(!searchtext.isEmpty())
baseQuery = baseQuery + " AND upper(title) like '%" + searchtext.toUpperCase() + "%'" ;
if(!movie_year.isEmpty())
baseQuery = baseQuery + " AND year=" + movie_year;
if(!movie_director.isEmpty())
baseQuery = baseQuery + " AND upper(director) like '%" + movie_director.toUpperCase() + "%'";
if( !star_firstName.isEmpty())
baseQuery = baseQuery + " AND upper(first_name) like '%" + star_firstName.toUpperCase() + "%'" ;
if( !star_lastName.isEmpty())
baseQuery = baseQuery + " AND upper(last_name) like '%" + star_lastName.toUpperCase() + "%'" ;
if(!title1.isEmpty() ){
baseQuery = "SELECT m.id, title, year, director, banner_url, trailer_url FROM movies m where m.title like '" + title1 + "%" + "'";
}
if( !genre.isEmpty()){
baseQuery = "SELECT m.id, title, year, director, banner_url, trailer_url FROM movies m, genres g, genres_in_movies gim where g.id=gim.genre_id and m.id = gim.movie_id and g.name='" + genre + "'";
}
System.out.println(baseQuery);
ResultSet resultSet = statement.executeQuery(baseQuery);
答案 0 :(得分:0)
在这种情况下,PreparedStatement
无法帮助您。
如果查询保持不变,则PreparedStatement
仅有助于提高性能,所有变化都是常量。
PreparedStatement
的另一个用途是避免SQL注入的危险。
如果这就是你所追求的,你可以像这样(未经测试)继续:
java.util.Vector<String> params = new Vector();
StringBuffer baseQuery = new StringBuffer("SELECT ...");
...
if (!dweebnoid.isEmpty()) {
baseQuery.append(" AND upper(dweebnoid) LIKE ?");
params.add("%" + dweebnoid + "%");
}
...
java.sql.PreparedStatement pstmt =
conn.prepareStatement(baseQuery.toString());
for (i=0; i<params.size();++i)
pstmt.setString(i+1, params.get(i));
java.sql.ResultSet resultSet = pstmt.executeQuery();