2013-06-20 52 views
0

我正在处理我的resultset以获取详细信息。我需要返回一个ArrayList,所以我怎样才能把resultset的密钥值从任何集合对象中提取出来,然后把它们放到ArrayList将结果集值放入Collection对象,然后添加到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; 

    } 
+0

什么问题?你尝试了什么? – yatul

+2

但你几乎拥有它!我想你必须为每一行实例化一个“Bike”,把名字和模型放在那里(构造函数或setters?),然后调用'bikeList.add(bike)'...就是这样。 – Fildor

回答

3

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

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

有没有办法以类不可知的方式做到这一点,即不必去查看每个属性?它可以干净地转换为列表? – joelc

2

你会实例化一个对象自行车和设置属性,你从结果集读取,那么自行车对象添加到ArrayList中,不是它,你在找什么?

2

你在你的hand..just有香蕉吃了:)

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

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; 
2
while (rs.next()) { 
    Bike bike = new Bike(); 
    bike.setName(rs.getString("name")); 
    bike.setModel(rs.getString("model")); 
    bikeList.add(bike); 
} 
2

我不知道该怎么你的自行车类的样子,但你应该做这样的方式:

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) 
} 
0

您需要实例自行车在while循环,并加入到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;