【发布时间】:2012-07-07 16:32:01
【问题描述】:
我正在尝试设置一个线程,该线程每 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 不能赋值,因为它是在封闭类型中定义的
【问题讨论】:
-
其他问题:1) 你不应该在 Swing 事件线程上调用
Thread.sleep(...)。 2)您应该在相对于 Swing 事件线程的后台线程中进行数据库调用。 3) 上面的代码都不应该在静态域中,在 main 方法中。顺便说一句,对@MJB 的回答加分。