优化查询而不是使用偏移量,限制和排序依据

时间:2017-07-12 08:46:40

标签: java query-optimization limit offset h2db

我是java的新手,我遇到了一个小问题。 实际上我从表中提取包含7345987条记录的数据并将其显示在jtable上。 到目前为止,我已成功使用Limitoffset

我的查询是:

ResultSet rs1 = stmt1.executeQuery(
                "SELECT ANUMBER,BNUMBER,DATETIME FROM CDR LIMIT '" + recordPerPage + "' OFFSET '" + offSet + "' ");

我已将recordPerPage设置为100000,将offset设置为0(对于第1页),对于第2页,我将offset增加到100001,依此类推......

但我希望按order byDATETIME结果。当我在order by之前尝试在我的查询中使用limit and offset时。它需要花费时间,因为首先它order by整个表,然后在页面之间的每次迭代中应用limit and offset

但我想要的是它应该使用order一次然后在该结果集上应用limit和offset。这种情况下的解决方案是什么?

以下是我完整的代码,了解我在做什么。

public class Try {

    static Connection conn;
    static JPanel panel;
    static DefaultTableModel model = new DefaultTableModel();
    static JTable table = new JTable(model);
    static JButton fButton, lButton, pButton, nButton;
    static int buttonID;
    static int totalRows;
    static int recordPerPage = 100;
    static int totalPages = 0;
    static int offSet = 0;
    static String x = "", y = "", z = "", inputValue = "";
    static int currentPage = 1;
    static JTextField pagingInput;

    private static JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    createAndShowGUI();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        });
    }

    protected static void createAndShowGUI() throws SQLException {
        JFrame frame = new JFrame();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(30, 50, 1300, 600);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        frame.setContentPane(contentPane);

        UIManager.put("TabbedPane.selected", Color.lightGray);
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.setBorder(new EmptyBorder(10, 10, 10, 10));
        frame.add(tabbedPane);

        panel = new JPanel();
        tabbedPane.addTab("TABLE", null, panel, null);
        tabbedPane.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 16));
        panel.setBackground(Color.white);
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        JPanel panel_1 = new JPanel();
        tabbedPane.addTab("GRAPH", null, panel_1, null);
        panel_1.setBackground(Color.white);

        JTable table = new JTable();
        panel.add(table);
        table.setFillsViewportHeight(true);

        createDBConnection();
    }

    private static void createDBConnection() throws SQLException {
        try {
            Class.forName("org.h2.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection("jdbc:h2:file:G:/hs_data/h2_db/test", "sa", "sa");
        } catch (SQLException e) {
            System.out.println("Unable to make connection with DB");
            e.printStackTrace();
        }
        createPaginationButtons(conn);
    }

    private static void createPaginationButtons(Connection conn) throws SQLException {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT count(*) FROM cdr");
        while (rs.next()) {
            totalRows = rs.getInt(1);
        }
        // int v = totalRows % recordPerPage == 0 ? 0 : 1;
        totalPages = totalRows / recordPerPage;
        createButton(totalPages);
    }

    private static void createButton(int totalPages) throws SQLException {

        fButton = new JButton("FIRST");
        lButton = new JButton("LAST");
        pButton = new JButton("PREVIOUS");
        nButton = new JButton("NEXT");
        pagingInput = new JTextField(10);
        Font bigFont = pagingInput.getFont().deriveFont(Font.PLAIN, 17f);
        pagingInput.setFont(bigFont);

        fButton.addActionListener(buttonlistener);
        lButton.addActionListener(buttonlistener);
        pButton.addActionListener(buttonlistener);
        nButton.addActionListener(buttonlistener);
        pagingInput.addActionListener(inputlistener);

        fButton.setBackground(new Color(26, 82, 118));
        lButton.setBackground(new Color(26, 82, 118));
        pButton.setBackground(new Color(26, 82, 118));
        nButton.setBackground(new Color(26, 82, 118));

        fButton.setForeground(Color.white);
        lButton.setForeground(Color.white);
        pButton.setForeground(Color.white);
        nButton.setForeground(Color.white);

        fButton.setEnabled(false);
        pButton.setEnabled(false);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(fButton);
        buttonPanel.add(pButton);
        buttonPanel.add(pagingInput);
        buttonPanel.add(nButton);
        buttonPanel.add(lButton);

        panel.add(buttonPanel);

        createTable(offSet);

    }

    static ActionListener inputlistener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            inputValue = pagingInput.getText();
            try {
                buttonID = Integer.parseInt(inputValue);
                offSet = (buttonID * recordPerPage) + 1;
                currentPage = buttonID;
                populateTable(offSet);
            } catch (NumberFormatException e2) {
                JOptionPane.showMessageDialog(null, "Please Enter Only Integers From 1 to'" + totalPages + "'");
                // e2.printStackTrace();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }

        }
    };

    static ActionListener buttonlistener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() instanceof JButton) {
                String text = ((JButton) e.getSource()).getText();
                if (text == "FIRST") {
                    offSet = 0;
                    currentPage = 1;
                } else if (text == "LAST") {
                    offSet = (totalPages * recordPerPage) + 1;
                    currentPage = totalPages;
                } else if (text == "NEXT") {
                    offSet = (currentPage * recordPerPage) + 1;
                    currentPage++;
                } else if (text == "PREVIOUS") {
                    if (currentPage == 2) {
                        offSet = 0;
                        currentPage--;
                    } else {
                        offSet = offSet - recordPerPage;
                        currentPage--;
                    }
                }

                if (currentPage >= totalPages) {
                    fButton.setEnabled(true);
                    pButton.setEnabled(true);
                    lButton.setEnabled(false);
                    nButton.setEnabled(false);
                }
                if (currentPage <= 1) {
                    fButton.setEnabled(false);
                    pButton.setEnabled(false);
                }
                if (currentPage > 1) {
                    fButton.setEnabled(true);
                    pButton.setEnabled(true);
                }
                try {
                    populateTable(offSet);
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }

        }
    };

    private static void createTable(int offSet) throws SQLException {

        model.addColumn("ANUMBER");
        model.addColumn("BNUMBER");
        model.addColumn("DATETIME");

        DefaultTableCellRenderer headerRenderer = new DefaultTableCellRenderer();
        headerRenderer.setBackground(new Color(26, 82, 118));
        headerRenderer.setForeground(Color.white);
        for (int i = 0; i < table.getModel().getColumnCount(); i++) {
            table.getColumnModel().getColumn(i).setHeaderRenderer(headerRenderer);
        }
        table.getTableHeader().setPreferredSize(new Dimension(30, 30));

        UIDefaults defaults = UIManager.getLookAndFeelDefaults();
        if (defaults.get("Table.alternateRowColor") == null)
            defaults.put("Table.alternateRowColor", new Color(240, 240, 240));
        panel.add(new JScrollPane(table));
        populateTable(offSet);
    }

    public static void populateTable(int offSet2) throws SQLException {

        model.setRowCount(0);
        Statement stmt1 = conn.createStatement();
        ResultSet rs1 = stmt1.executeQuery(
                "SELECT ANUMBER,BNUMBER,DATETIME FROM CDR LIMIT '" + recordPerPage + "' OFFSET '" + offSet + "' ");
        while (rs1.next()) {
            x = rs1.getString("ANUMBER");
            y = rs1.getString("BNUMBER");
            z = rs1.getString("DATETIME");
            model.addRow(new Object[] { x, y, z });

        }
        table.setRowHeight(25);
    }

}

0 个答案:

没有答案