有一张表 student
id   name
1    tom
2    jack
3    rose
4    mary求问:执行以下代码,为什么最后只有一条记录,就是表中最后一条谢谢。Connection conn = DBConnect.getInstance().getConnection();
conn.setAutoCommit(false);
String sql = "select * from student where id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
int[] ids = {1,2,3,4};
for(int i:ids){
    ps.setLong(1, i);
    ps.addBatch();
}
ResultSet rs = ps.executeQuery();
int num = 0;
while (rs.next()) {
    num++;
    System.out.println(rs.getLong(1) + " " + rs.getString(2));
}
System.out.println("num of test:" + num);
conn.setAutoCommit(true);

解决方案 »

  1.   

    int[] ids = {1,2,3,4};
    for(int i:ids){
        ps.setLong(1, i);
        ps.addBatch();
    }循环结束的时候 i=4 所以你的  ResultSet rs = ps.executeQuery(); 执行的时候等同于 select * from student where id = 4需要修改你的程序。 比如 where find_in_set(id,'1,2,3,4');
      

  2.   

    不可以把所有的结果都存到一个ResultSet里面吗?
    有什么方法可以批量查询?
      

  3.   

    一个SQL SELECT语句回返回一个 ResultSet 。
      

  4.   

    PreparedStatement的batch一般是用来insert或者update的。像select,一般都是用sql来解决,不会说一次发送一批查询语句的。你这里要么改sql,要么就多次查询多次取结果集。或者用存储过程拼动态sql的方式实现。