我正在尝试设置一个线程,该线程每 100 毫秒循环一次,每次迭代都会查询 SQL 数据库中的表。这是我的公共静态无效主类中的内容。如何在侦听器之外定义连接并仅在循环中调用查询?
// Database credentials
final String url = "jdbc:mysql://192.168.0.0/";
final String db = "db";
final String driver = "com.mysql.jdbc.Driver";
final String table = "table";
public final Connection conn = null;
// Define listner
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
System.out.println("Reading Info.");
try {
Class.forName(driver);
try {
conn = DriverManager.getConnection(url+db,"root","pass");
Statement st = (Statement) conn.createStatement();
String sql = "";
st.executeUpdate(sql);
conn.close();
} catch (SQLException s) {
s.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR: Please try again!");
}
} catch (ClassNotFoundException cnfe){
JOptionPane.showMessageDialog(null, "ERROR:");
}
}
};
Timer timer = new Timer( 100 , taskPerformer);
timer.setRepeats(true);
timer.start();
Thread.sleep(100);
}
现在它给了我以下错误:
线程“AWT-EventQueue-0”java.lang.Error 中的异常:未解决的编译问题:无法分配最终的局部变量 conn,因为它是在封闭类型中定义的