2013-06-20 73 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;