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

lb3vh1jj  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(321)

我正在尝试学习如何将数据保存到数据库或从数据库加载数据,但遇到了一个问题。现在我有一门课叫 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 wich具有以下功能:

public class Storage {

    private List<Component> stock;

在其他类中,我可以创建save和load方法,因为它们只有简单的变量,比如string或integer,但是对于这些类,我完全迷失了方向,因为不仅有要保存/返回的列表,还有递归列表。到目前为止,我对组件的了解是:

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

有例外需要处理,但在这方面我认为我很好。另外,如果我能为组件做这个,我可能也能为存储设置它,所以现在我认为这个问题已经足够大了。

vsikbqxv

vsikbqxv1#

根据我对你问题的理解。你可能需要 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;
}

相关问题