开发者社区 问答 正文

关于Dbutils中,输入数量不确定的条件:报错

v 百度了好久都没找到解决方案,求解决
假如有一个数组里面存储了很多id,现在想通过一条语句全部查出来该怎么做?
我想到的方式是使用in,但是这样写就要手动拼接sql语句了,有点坑爹。。
select * from tables where id in (xxx,xxx,xxx)

preparedstatment貌似也没办法写。。

展开
收起
kun坤 2020-06-09 11:52:52 557 分享 版权
1 条回答
写回答
取消 提交回答
  • 只想了个简单的办法:
    用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); } }

    ######

    引用来自“莱昂纳多”的答案

    只想了个简单的办法: 用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); } }
    QAQ我目前的方法就是这样,但是似乎效率比较差,所以我想使用in看看有没有提升=。= 还是谢谢~
    2020-06-09 11:53:04
    赞同 展开评论
问答分类:
问答地址: