我需要将连接池对象传递给 ScheduledExecutorService 线程,但这样做有困难。我试图在声明前添加final,但这会引发以下错误...无法分配最终的局部变量连接。它必须为空白且不使用复合赋值
如何正确传递这个连接对象?
public class AdminManager extends JFrame {
private JPanel contentPane;
private JTable tableQueue;
private JTable tableFilled;
/**
* Launch the application.
* @throws InterruptedException
*/
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 {
// load the database driver (make sure this is in your classpath!)
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.0.0.1:3306/db"); // jdbc url specific to your database, eg jdbc:mysql://127.0.0.1/yourdb
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();
}
}
}
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable(){
@Override
public void run(){
System.out.println("Working ... ");
String sql = "SELECT * FROM table;";
Statement st;
try {
st = connection.createStatement();
ResultSet rs = st.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 2000, 1000, TimeUnit.MILLISECONDS);