将结果集值放入Collection对象,然后添加到ArrayList

时间:2013-06-20 06:17:27

标签: java sql collections map resultset

我正在处理我的resultset以获取详细信息。我需要返回ArrayList,那么如何将resultset中的键值放到任何集合对象中,然后将它们放到ArrayList

以下是代码:

public List<Bike> addBikes() throws ClassNotFoundException, SQLException{
        List<Bike> bikeList = new ArrayList<Bike>();

        Class.forName("com.mysql.jdbc.Driver");
        Connection con  = null;
        Statement  stm = null;
        ResultSet rs = null;
        con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ;
        stm=con.createStatement(); 
        String qry="Select * from bike"; 
        rs=stm.executeQuery(qry);
        while(rs.next())
        {           
            /* I need to put   
             * rs.getString("name"),rs.getString("model")
             * etc into any of the suitable collection objects 
             * and then need to add those to the ArrayList - bikeList
             * 
             */

        }
        return bikeList;

    }

6 个答案:

答案 0 :(得分:3)

对于结果集中的每个结果,创建一个new Bike()并将该结果中的值复制到新的自行车字段。最后,将自行车添加到列表中。

Bike bike = new Bike()
bike.setName(rs.getString("name"));
//...
bikeList.add(bike);

答案 1 :(得分:2)

你会实例化一个Bike对象并设置你从结果集中读取的属性,然后将自行车对象添加到你的arraylist中,不是你想要的吗?

答案 2 :(得分:2)

你手里拿着香蕉......只吃它:)

创建一个空列表并在迭代中创建新的Bike并添加到List中。

 List<Bike> bikes  = new ArrayList<Bikes>();
  while(rs.next())
        {           
           Bike bike = new Bike();
           bike.setname( rs.getString("name"));
           //other properties
           bikes.add(bike);
        }

    return bikes;

答案 3 :(得分:2)

while (rs.next()) {
    Bike bike = new Bike();
    bike.setName(rs.getString("name"));
    bike.setModel(rs.getString("model"));
    bikeList.add(bike);
}

答案 4 :(得分:2)

我不知道你的Bike类是怎么样的,但你应该这样做:

while(rs.next())
{
    String column1 = rs.getString("column1_name");
    .... and the others columns

    Bike bike = new Bike();

    bike.setColumn1(column1);
    .... and others...

    bikeList.add(bike)
}

答案 5 :(得分:0)

您需要在while循环中实例化Bike并添加到List

 List<Bike> bikes  = new ArrayList<>();
 while(rs.next())
    {           
       Bike bike = new Bike();
       bike.setname( rs.getString("name"));
       //other properties
       bikes.add(bike);
    }

  return bikes;