Search code examples
javasqlcollectionsdictionaryresultset

Put resultset values into Collection object then add to ArrayList


I was processing my resultset to get the details. I need to return an ArrayList, so how can I put the key,values from the resultset to any of the collection objects and then put the same to an ArrayList?

Here is the code:

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;

    }

Solution

  • For each result in the result set, create a new Bike() and copy the values from that result to the new bikes fields. At the end, add the bike to the list.

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