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

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

这是代码:

 public List addBikes() throws ClassNotFoundException, SQLException{ List bikeList = new ArrayList(); 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; } 

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

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

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

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

我不知道你的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) } 

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

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

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

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

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