2012-07-07 57 views
0

如何将SQL连接传递给Action Listener。我想要一个无限循环,睡100ms。假设循环的每一次迭代都要查询数据库。摆动计时器是做这件事的最好方法吗?如果是的话,我怎样才能将连接传递给Action Listener。如果没有,有人可以请告知如何做到这一点。非常感谢。将SQL连接传递给ActionListener(线程)

代码:

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. 
} 
+0

你为什么使用'javax.swing.Timer'?我没有看到你在使用任何Swing组件。也许你应该使用'Executors' /'ScheduledExecutorService'类? – user1329572 2012-07-07 21:07:44

回答

1

不要javax.swing.Timer类定期执行非Swing任务。相反,使用ScheduleExecutorService

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); 
exec.schedule(new Runnable(){ 
    @Override 
    public void run(){ 
     // query database 
    } 
}, 0, 100, TimeUnit.MILLISECONDS); 
+0

所以我应该把ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();部分在我的主类,然后把其余的另一种方法,并调用该方法? – scriptdiddy 2012-07-07 21:46:17

+0

好的,但是如何将连接传递到ScheduledExecutorService? – scriptdiddy 2012-07-08 17:32:19

1

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