将结果集值放入Collection对象,然后添加到ArrayList [英] Put resultset values into Collection object then add to ArrayList

查看:465
本文介绍了将结果集值放入Collection对象,然后添加到ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理我的 resultset 以获取详细信息。我需要返回一个 ArrayList ,所以我怎么把密钥,值从 resultset 到任何集合对象,然后将相同的 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?

这是代码:

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()并将值从该结果复制到新的自行车字段。

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);

这篇关于将结果集值放入Collection对象,然后添加到ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆