从循环中获取ResultSet,同时将其添加到List

时间:2017-05-24 08:34:07

标签: java jdbc

我有一个List getter方法,返回ResultSet。每次ResultSet次循环都会将其添加到List。但是在我的ActionListener中,我有一个循环,每次都会更改值,并且还会给出另一个ResultSet。如何在调用getter方法时避免List创建另一个实例?

public List <Model> get(Model model) 
{
    String query = "{call get(?,?,?,?)}";
    List <Model> list = new ArrayList();

    try(Connection con = DBUtil.getConnection(DBType.MYSQL);
        CallableStatement cs = con.prepareCall(query);)
    {
        cs.setInt(1, model.getName());
        cs.setString(2, model.getPosition());
        cs.setString(3, model.getDepartment());
        cs.setString(4, model.getDate());

        try(ResultSet rs = cs.executeQuery())
        {
            while(rs.next())
            {
                Model m = new Model();

                m.setIn(rs.getString(1));
                m.setOut(rs.getString(2));

                list.add(m);

            }
        }
    }
    catch(SQLException ex)
    {
        System.err.println("Error "+ex.getSQLState());
    }
    return list;
}

在动作侦听器中调用它。

for(int i = 0; i < myList.size(); i++)
{
    model.setName("Anything");
    model.setPosition("Jr");
    model.setDepartment("It");
    model.setDate(myList.get(i));

    DAO.get(model);
}

正如你在这里看到的,循环每次循环时都会给出新值。我的问题是在结果集循环中执行一行后,getter方法重置为零。

1 个答案:

答案 0 :(得分:1)

如果您想收集所有get()次调用中的元素,则有两种解决方案。

将返回的元素收集到调用循环中的单个列表中:

ArrayList<Model> list = new ArrayList<>(); 
for(int i = 0; i < myList.size(); i++)
{
    model.setName("Anything");
    model.setPosition("Jr");
    model.setDepartment("It");
    model.setDate(myList.get(i));

    list.addAll(DAO.get(model)); //Get elements, and add them to the list
}

...或者将public List <Model> get(Model model)更改为public List<Model> get(Model model, List<Model> list),而不是为get()的每次调用创建新列表,并将其传递给相同的列表:

public List<Model> get(Model model, List<Model> list) 
{
    String query = "{call get(?,?,?,?)}";

    try(Connection con = DBUtil.getConnection(DBType.MYSQL);
        CallableStatement cs = con.prepareCall(query);)
    {
        cs.setInt(1, model.getName());
        cs.setString(2, model.getPosition());
        cs.setString(3, model.getDepartment());
        cs.setString(4, model.getDate());

        try(ResultSet rs = cs.executeQuery())
        {
            while(rs.next())
            {
                Model m = new Model();

                m.setIn(rs.getString(1));
                m.setOut(rs.getString(2));

                list.add(m);

            }
        }
    }
    catch(SQLException ex)
    {
        System.err.println("Error "+ex.getSQLState());
    }
    return list;
}

然后像这样调用get()

ArrayList<Model> list = new ArrayList<>(); 
for(int i = 0; i < myList.size(); i++)
{
    model.setName("Anything");
    model.setPosition("Jr");
    model.setDepartment("It");
    model.setDate(myList.get(i));

    DAO.get(model,list);
}