v 百度了好久都没找到解决方案,求解决
假如有一个数组里面存储了很多id,现在想通过一条语句全部查出来该怎么做?
我想到的方式是使用in,但是这样写就要手动拼接sql语句了,有点坑爹。。
select * from tables where id in (xxx,xxx,xxx)
preparedstatment貌似也没办法写。。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
只想了个简单的办法:
用preparedstatment实现,for循环遍历数组元素,在for循环中设置preparedstatement参数,最终将所有查询结果作为对象放入一个list并返回。
以student表为例,字段:id ,name,age,sex:
public static List<Student> getDataByArray(int[] arry) throws SQLException{ Connection con=null; PreparedStatement pst=null; ResultSet rs=null; try{ con=DbUtils.openConnection(); String sql="select id,name,age,sex from student where id=?"; pst=con.prepareStatement(sql); List<Student> list=new ArrayList<Student>(); for(int i=0;i<arry.length;i++){ int n=arry[i]; pst.setInt(1, n); rs=pst.executeQuery(); Student stu=new Student(); if(rs.next()){ stu.setId(rs.getInt("id")); stu.setName(rs.getString("name")); stu.setAge(rs.getInt("age")); stu.setSex(rs.getString("sex")); list.add(stu); } } return list; }catch(SQLException e){ e.printStackTrace(); throw e; }finally{ DbUtils.closeConnection(con, pst, rs); } }
######