关于where条件查询追加字段的问题

it-er 2011-05-26 01:45:14

String sqlstr = "select * from Table where ";
int a = Integer.parseInt(request.getParameter("a"));
int b = Integer.parseInt(request.getParameter("b"));
int c = Integer.parseInt(request.getParameter("c"));
int d = Integer.parseInt(request.getParameter("d"));

if (a!= -1)
sqlstr = sqlstr + " a=" + a;
if (b != -1)
sqlstr = sqlstr + " and b=" + b;
if (c != -1)
sqlstr = sqlstr + " and c=" + c;
if (d!= -1)
sqlstr = sqlstr + " and d=" + d;

如果第一个字段a为空的话,会变成select * from Table where and b=... 这样会报错,以前一直用where1=1来处理的,现在因为这张表数据量比较大,会影响性能。so想问一下大家还有没有其他方法?
...全文
141 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
duan 2011-05-26
  • 打赏
  • 举报
回复
String 换成StringBuffer,性能上会不会更好一点??
it-er 2011-05-26
  • 打赏
  • 举报
回复
谢谢各位!
zhouyusunquan 2011-05-26
  • 打赏
  • 举报
回复
加上1=1反而会加快速度,还有,你的条件数比and数要小一个,这样也可以判断
龙四 2011-05-26
  • 打赏
  • 举报
回复
1=1怎么影响性能,这个条件又不会去操作真实的数据?!
龙四 2011-05-26
  • 打赏
  • 举报
回复
在所有的and前面加上“1=1”
qybao 2011-05-26
  • 打赏
  • 举报
回复
have a try
String temp = "";
if (a!= -1)
temp = temp + " a=" + a;
if (b != -1) {
if (temp.length > 0) {temp = temp + " and";}
temp = temp + " b=" + b;
}
if (c != -1) {
if (temp.length > 0) {temp = temp + " and";}
temp = temp + " c=" + c;
}
if (d!= -1) {
if (temp.length > 0) {temp = temp + " and";}
temp = temp + " d=" + d;
}
sqlstr = sqlstr + temp

81,095

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧