如何將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.
}
你爲什麼使用'javax.swing.Timer'?我沒有看到你在使用任何Swing組件。也許你應該使用'Executors' /'ScheduledExecutorService'類? – user1329572 2012-07-07 21:07:44