0

我正在处理我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;

    }
4

6 回答 6

4

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

Bike bike = new Bike()
bike.setName(rs.getString("name"));
//...
bikeList.add(bike);
于 2013-06-20T06:22:08.957 回答
3

你手里拿着香蕉……吃吧:)

创建一个空列表并在迭代中创建新自行车并添加到列表中。

 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;
于 2013-06-20T06:22:35.873 回答
2

您将实例化一个 Bike 对象并设置从结果集中读取的属性,然后将 Bike 对象添加到您的数组列表中,这不是您要找的吗?

于 2013-06-20T06:22:22.637 回答
2
while (rs.next()) {
    Bike bike = new Bike();
    bike.setName(rs.getString("name"));
    bike.setModel(rs.getString("model"));
    bikeList.add(bike);
}
于 2013-06-20T06:22:49.697 回答
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)
}
于 2013-06-20T06:25:09.443 回答
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;
于 2013-06-20T09:08:07.283 回答