上例子:
①使用1=1
String sql =Select A.x,A.Y FROM table A Where 1=1;
StringBuffer sqlBuffer = new StringBuffer ;
sqlBuffer.append(sql);
如果画面有三个独立的可选输入项目l,m.n
if ( l != null ) {
sqlBuffer.append("and A.l = l");
}
if ( m != null ) {
sqlBuffer.append("and A.m = m");
}
if ( n != null ) {
sqlBuffer.append("and A.n= n");
}
这个是使用了“1=1”的用法,直接判断追加就行。
②不使用1=1,至少要有如下繁琐的判断
String sql =Select A.x,A.Y FROM table A ;
StringBuffer sqlBuffer = new StringBuffer ;
sqlBuffer.append(sql);
if (l != 空) {
sqlBuffer.append("where A.l = l");
} else {
if (m != 空) {
sqlBuffer.append("where A.m = m");
} else {
if (n != 空)
sqlBuffer.append("where A.n = n");
}
}
if (l != 空 and m != 空) {
sqlBuffer.append(" and A.m = m");
}else if (l != 空 and m != 空 and n != 空) {
sqlBuffer.append(" and A.n = n");
}
晕了吧,呵呵,我都要写晕了,为牺牲掉的脑细胞祈祷下。
每一个项目的追加都要判断前面的检索条件是否存在,以确定是否要“where”。一个晕乎可能还会有漏网之项。
有了上面的比较1=1的优势就比较明显了。小小的一点变通让你和你的程序不再繁琐~~O(∩_∩)O~~