方法1.例如:
StringBuffer sql = new StringBuffer();
sql.append("from Book b where 1=1 ");
if(!"".equals(sum)&&sum!=null){
sql.append(" and b.sum ='"+sum+"'");
}
if(!"".equals(aut)&&aut!=null){
sql.append(" and b.author ='"+aut+"'");
}
if(!"".equals(pub)&&pub!=null){
sql.append(" and b.publish ='"+pub+"'");
}
if(!"".equals(rfid)&&rfid!=null){
sql.append(" and b.addRfidSum ='"+rfid+"'");
}
方法2.
StringBuffer sql = new StringBuffer();
sql.append("from Book b where ");
if(!"".equals(sum)&&sum!=null){
sql.append(" b.sum ='"+sum+"' and ");
}
if(!"".equals(aut)&&aut!=null){
sql.append(" b.author ='"+aut+"' and ");
}
if(!"".equals(pub)&&pub!=null){
sql.append(" b.publish ='"+pub+"' and ");
}
if(!"".equals(rfid)&&rfid!=null){
sql.append(" b.addRfidSum ='"+rfid+"' and ");
}
String s = sql.toString();
s=s.substring(0,s.lastIndexOf(" and ")>0? s.lastIndexOf(" and "):s.indexOf("where"));
System.out.println(s);
当心在单引号和双引号中间不要有空格,不然会出错