使用向前和向后导航结果集

时间:2013-01-19 10:29:07

标签: java sql

在java中,如果我们想要导航结果集,我们通过向前和向后使用2个按钮来执行查询。我们可以执行此任务的方式是什么

    private void nextActionPerformed(java.awt.event.ActionEvent evt) {                                            
        if(evt.getSource()==bt_previous){
        DBUtil util = new DBUtil();
             try {
                        Connection con = util.getConnection();
                        PreparedStatement stmt = con.prepareStatement("SELECT * FROM DETAILS where id=?");
                        ResultSet rs;
                        String rm = id.getText().trim();
                        stmt.setLong(1, Long.parseLong(rm));
                        rs = stmt.executeQuery();
                        while(rs.next()){

                        String a = rs.getString("weight");
                        txtboxwgt.setText(a);
                        String b = rs.getString("note_state");
                        cbnotstat.setSelectedItem(b);
                        String c = rs.getString("dm_state");
                        cbdmnstat.setSelectedItem(c);
                                      }
                   } catch (Exception e) {
                             JOptionPane.showMessageDialog(null, e.getMessage());
                         }
            }


        } 

2 个答案:

答案 0 :(得分:1)

您需要对结果进行分页。 AFAIK结果集没有简单的任务,没有内置功能。 您有以下选择:

  1. 将每一行转换为对象,并实际显示对象。保留到目前为止显示的页面列表,并根据需要提供它们(用于向后移动)并使用结果集进行转发。但是,这有其局限性:如果您有足够的物体,您可能会达到系统内存的限制,因此除非您知道有少量物体,否则不建议这样做。

  2. 使用其他数据库表进行分页。 为此,请创建一个包含结构的附加表:pageitem_id。将其命名为history_table。然后读取前50个对象(假设您希望一次显示50行)。即第1页。在历史记录表中插入唯一标识符以及页码。 如果需要向后移动,请阅读上一页中的唯一ID。前进时,执行选择。

  3. 前进的sql语句如下所示:

    select * from my_table a where not exists (select 1 from history_table h where a.item_id = h.item_id)
    

    您执行所需的每个页面(即使是第一个!)

    应使用batch insert

    在数据库中插入先前的读取元素

答案 1 :(得分:1)

制作实体类Detail

public class Detail {
    private String weight;
    private String noteState;
    private String dmState;

    public Detail() {

    }

    public Detail(String weight, String noteState, String dmState) {
        this.weight = weight;
        this.noteState = noteState;
        this.dmState = dmState;
    }
    // getters and setters below
}

在迭代结果集时,在nextActionPerformed方法中,创建实体的新实例并将其添加到某个集合中,即LinkedList

                List<Detail> allDetails = new LinkedList<Detail>();
                while(rs.next()) {

                    String a = rs.getString("weight");
                    String b = rs.getString("note_state");
                    String c = rs.getString("dm_state");
                    allDetail.add(new Detail (a, b, c));
                }

然后,您可以allDetails支持的任何方式浏览LinkedList。如果LinkedList不符合您的需求,请考虑使用其他集合。

相关问题