where 1=1低效,被迫進行全表掃描,執行效率不高,爲進行數據檢索性能優化,要避免出現where 1=1.
拼接字符串查詢數據,有時候有多個可選條件由用戶選擇時,不能確定在哪個條件前加where,那個條件前加and,可以用這種方法:
/**
* where 1=1替換* @param sql
* @param hasWhere
* @return
*/
public boolean appendWhereIfNeed(StringBuffer sql,boolean hasWhere){
if(hasWhere==false){
sql.append("WHERE");
}else{
sql.append("AND");
}
return true;
}
/**
*
* 根據條件查詢
*
*/
public ActionForward OnSearch(ActionMapping mapping, ActionFormBase form, HttpServletRequest request,
HttpServletResponse response, ActionForward forward) throws Exception {
String param1= request.getParameter("param1");//前臺傳值
String param2= request.getParameter("param2");//前臺傳值
String param3= request.getParameter("param3");//前臺傳值
String param4= request.getParameter("param4");//前臺傳值
boolean hasWhere=false;
StringBuffer sSQL=new StringBuffer("");
if (param1!= null && !"".equals(param1)) {
hasWhere=appendWhereIfNeed(sSQL,hasWhere);
sSQL.append(" A.F_LICENSE_PLATE like '%" + param1+ "%' ");
}
if (param2!= null && !"".equals(param2)) {
hasWhere=appendWhereIfNeed(sSQL,hasWhere);
sSQL.append(" A.F_LEVEL='" + param2+ "' ");
}
if (param3!= null && !"".equals(param3)) {
hasWhere=appendWhereIfNeed(sSQL,hasWhere);
sSQL.append(" A.F_INSURANCE='" + param3+ "' ");
}
if (param4!= null && !"".equals(param4)) {
hasWhere=appendWhereIfNeed(sSQL,hasWhere);
sSQL.append(" A.F_DRIVER='" + param4+ "' ");
}
sSQL.append(" ;");
executeSQL(sql);//執行SQL語句
return forward;
}
--程序員的SQL金典