I’m trying to setup a thread that loops every 100ms with every iteration querying a table in a SQL database. Here is what I have in my public static void main class. How can I define the connection outside of the listener and only call the query in the loop?
// 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);
}
Right now it’s giving me the following error:
Exception in thread “AWT-EventQueue-0” java.lang.Error: Unresolved compilation problem:
The final local variable conn cannot be assigned, since it is defined in an enclosing type
You don’t want to. Connections are not thread safe per JDBC specification. Hence there is no reason or justification for Connection variable not being local to the thread. Why isn’t it?