Java 将结果集值放入集合对象,然后添加到ArrayList
我正在处理结果集以获取详细信息。我需要返回一个ArrayList,那么如何将结果集中的键、值放入任何集合对象,然后将其放入ArrayList 代码如下:Java 将结果集值放入集合对象,然后添加到ArrayList,java,sql,collections,map,resultset,Java,Sql,Collections,Map,Resultset,我正在处理结果集以获取详细信息。我需要返回一个ArrayList,那么如何将结果集中的键、值放入任何集合对象,然后将其放入ArrayList 代码如下: public List<Bike> addBikes() throws ClassNotFoundException, SQLException{ List<Bike> bikeList = new ArrayList<Bike>(); Class.forName("com.
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;
}
对于结果集中的每个结果,创建一个新的Bike并将该结果中的值复制到newbikes字段。最后,将自行车添加到列表中
Bike bike = new Bike()
bike.setName(rs.getString("name"));
//...
bikeList.add(bike);
您可以实例化一个Bike对象并设置从结果集中读取的属性,然后将Bike对象添加到arraylist中,这不是您要查找的对象吗?您手中有香蕉..只需吃它: 创建一个空列表,在迭代中创建新自行车并添加到列表中
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;
我不知道你的自行车课是什么样子,但你应该这样做:
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)
}
您需要在while循环中实例化Bike并将其添加到列表中
有什么问题吗?你尝试了什么?但你几乎成功了!你必须为每一行实例化一辆自行车,把名字和型号放在那里,构造器还是设置器?然后打电话给bikeList.addbike。。。就是这样。有没有一种方法可以以类不可知的方式做到这一点,即不必检查每个属性?它可以干净地转换为列表吗?
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)
}
List<Bike> bikes = new ArrayList<>();
while(rs.next())
{
Bike bike = new Bike();
bike.setname( rs.getString("name"));
//other properties
bikes.add(bike);
}
return bikes;