现在得项目有个需求,就是我接收到一个数组(里面存放的是id),这个数组的长度不确定,因情况不同,从十几到几千都有可能。我现在要做的就是按照数组中id序列,去数据库中查询出相应的结果(id是逐渐),要求查询出的结果就是按数组中id的序列排好的。比如:接收到的数组是 int[] ids = {1,9,3,7,6};我现在需要从数据库中查出的结果结构如下所示:
id name
1 张1
3 张3
9 张9
7 张7
6 张6
这个sql语句该如何构造?
id name
1 张1
3 张3
9 张9
7 张7
6 张6
这个sql语句该如何构造?
StringBuffer sb = new StringBuffer("select * from table1 where ");
for(int i = 0 ;i<ids.length;i++){
if(i!=ids.length){
sb.append(" id="+ids[i]+" or");
}else{
sb.append(" id="+ids[i]);
}
}
String sql="select * from table1 where id in ("+StringUtils.join(ids,",")+") order by id"
将commons-lang.jar包放入classpath
该库中有很多有用的工具方法,可以大大大的减少我们的编码量。
可以在http://commons.apacher.org下载
查询出来的结果就是按照这循序排出来的
String sql="select * from table1 where ids in";
String s="";
for(int i=0;i<ids.length;i++)
{
s+=ids[i]+",";
}
sql=sql+"("+s.substring(0,s.length()-1)+")";
System.out.println(sql);
比如:19376 放在list1中。2,接着你在for循环的查找你要查找19376 id的数据,在讲每一条返回回来的数据存储在一个bean中,然后再将这些分别的bean存储在 另外一个 ArrayList list2 中,
3,最后你在正对这个list2进行操作。
注明:这里值考虑实现,没有考虑运行效率等其他情况。