如何使用jdbc从数据库加载对象列表

问题描述 投票:1回答:1

我正在尝试学习如何在数据库中保存和加载数据,我遇到了一个问题。目前我有一个名为Component的课程,其中包含以下内容:

public class Componente {

    private int code;
    private String description;
    private double price;
    private int quantity;
    private List<Componente> previous;
    private List<Componente> incompatible;

我还有一个名为Storage的类,其中包含以下内容:

public class Storage {

    private List<Component> stock;

还有其他类我可以创建保存和加载方法,因为它们只有像String或Integers这样的简单变量,但是对于这些我完全丢失了,因为不仅有保存/返回的列表,而且还有递归列表。到目前为止我对组件的作用是:

public void save(Component c)throws SQLException{
    Connection con = null;

    con = Connect.connect();
    PreparedStatement st = con.prepareStatement("INSERT INTO component 
    VALUES(?,?,?,?,?,?)");

    st.setInt(1, c.getCode());
    st.setString(2, c.getDescription());
    st.setDouble(2, c.getPrice());
    st.setInt(2, c.getQuantity());
    //Missing the last 2 variables
    st.executeUpdate();

    con.close();
}

public Component load(Object key) throws SQLException {
    Component c = null;
    Connection con = Connect.connect();

    PreparedStatement ps = con.prepareStatement("select * from component 
    where code = ?");
    ps.setInt(1, code);
    ResultSet rs = ps.executeQuery();

    if(rs.next()){
        c = new 

       Component(rs.getInt("code"),rs.getString("description"),
       rs.getDouble("price"),rs.getInt("quantity"));
    }
    con.close();

    return c;
}

有一些例外需要处理,但在那部分我觉得我很好。此外,如果我能够为组件做这件事,我也可以将其设置为存储,所以现在我觉得这个问题已经够大了。

java mysql database
1个回答
1
投票

根据我对你的问题的理解。您可能需要使加载函数的return类型类似于列表;在rs.next()块中构建列表,并在完成后返回。

 public List<Component> load(Object key) throws SQLException { 
     List<Component> componentList= new ArrayList<Component>();
    Component c = null;
    Connection con = Connect.connect();

    PreparedStatement ps = con.prepareStatement("select * from component 
    where code = ?");
    ps.setInt(1, code);
    ResultSet rs = ps.executeQuery();

    if(rs.next()){
        c = new Component(rs.getInt("code"),rs.getString("description"),
                          rs.getDouble("price"),rs.getInt("quantity"));
        componentList.add(c);
    }
    con.close();

    return componentList;
}
© www.soinside.com 2019 - 2024. All rights reserved.