本文通过在SQL语句select 全部查询尾部添加where 1=1 ,从而实现后期条件拼接的便利,可以无限次添加 and =* and = and… …
这样,就能通过传入参数不同实现不同的查询
//查询全部新闻或某类新闻
public List<News> searchNews(String ntidS) {
getConn();
allNewsList = new ArrayList<News>();
try {
//借助”where 1=1”无条件全部查询,方便后续条件“and * = *”多次添加
sql = "select * from news where 1=1";
//判断传入参数是否为空
if (ntidS != null && !ntidS.equals("")) {
ntid = Integer.parseInt(ntidS);
sql = sql + " and ntid=?";
pst = conn.prepareStatement(sql);
//记得set占位符的值
pst.setInt(1, ntid);
} else {
//传入参数为空,则查询全部,无需拼接and条件语句部分
pst = conn.prepareStatement(sql);
}
System.out.println(sql);
rs = pst.executeQuery();
while (rs.next()) {
//循环第一步,先new一个News对象
news = new News();
news.setNid(rs.getInt("nid"));
news.setNtid(rs.getInt("ntid"));
news.setNtitle(rs.getString("ntitle"));
news.setNauthor(rs.getString("nauthor"));
news.setNcreatedate(rs.getString("ncreatedate"));
news.setNpicpath(rs.getString("npicpath"));
news.setNmodifydate(rs.getString("nmodifydate"));
news.setNsummary(rs.getString("nsummary"));
news.setNcontent(rs.getString("ncontent"));
//把设置好属性值的News对象添加进ArrayList。进入下次循环
allNewsList.add(news);
}
closeConn();
} catch (SQLException e) {
e.printStackTrace();
}
//返回新闻对象列表
return allNewsList;
}