0

如何将 SQL 连接传递给 Action Listener。我想要一个无限循环,它会休眠 100 毫秒。假设循环的每次迭代都查询数据库。摆动计时器是最好的方法吗?如果是这样,我如何将连接传递给动作侦听器。如果没有,有人可以建议如何做到这一点。非常感谢。

代码:

public static void main(String[] args) throws InterruptedException {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    AdminManager frame = new AdminManager();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        BoneCP connectionPool = null;
        Connection connection = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        try {
            // setup the connection pool
            BoneCPConfig config = new BoneCPConfig();
            config.setJdbcUrl("jdbc:mysql://192.162.0.0");
            config.setUsername("root"); 
            config.setPassword("");
            connectionPool = new BoneCP(config); // setup the connection pool

            connection = connectionPool.getConnection(); // fetch a connection

            if (connection != null){
                System.out.println("Connection successful!");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


        // Define listner
        ActionListener taskPerformer = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                //...Perform a task...

                String sql = "SELECT * table;";
                Statement st = connection.createStatement();
                ResultSet rs = st.executeQuery(sql);
                while(rs.next()) {
                    String symbol = rs.getString("name");
                    System.out.println(symbol);
                }

            }
            };
        Timer timer = new Timer( 100 , taskPerformer);
        timer.setRepeats(true);
        timer.start();

        Thread.sleep(1000);

        //connectionPool.shutdown(); // shutdown connection pool.
}
4

2 回答 2

1

不要让javax.swing.Timer类周期性地执行一个非 Swing 任务。相反,使用ScheduleExecutorService,

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.schedule(new Runnable(){
    @Override
    public void run(){
        // query database
    }
}, 0, 100, TimeUnit.MILLISECONDS);
于 2012-07-07T21:10:26.657 回答
1

如果后台任务必须不断更新 Swing 组件,请使用SwingWorker定期process()更新组件的模型。在此示例中,使用JTextArea从 H2 数据库获得的数据更新 a。

于 2012-07-08T02:15:42.840 回答