0
연결 풀 개체를 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);
하지만 새로운 클래스가 생성됩니까? 내가 제안한 내용과 일치하도록 코드를 바꿨습니다. \t AdminManager 유형의 인 클로징 인스턴스에 액세스 할 수 없습니다. AdminManager 유형의 엔 클로징 인스턴스 (예 : x.new A(), x는 AdminManager의 인스턴스)로 할당을 한정해야합니다. – scriptdiddy
@scriptdiddy : 클래스를 static으로 만들거나 작업중인 현재 클래스 외부로 이동하십시오. – Tudor
@scriptdiddy : 새 클래스를 만들기 전에 첫 번째 솔루션을 적용하려고 시도 했습니까? 업데이트 된 코드에서 새 클래스를 정의하지 않아도 작동합니다. 동일한 연결 개체에 대한 최종 참조를 정의하면됩니다. – Tudor