...
Code Block | ||
---|---|---|
| ||
class DBConnector implements Runnable { final String query; DBConnector(String query) { this.query = query; } private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() { Connection connection = null; @Override public Connection initialValue() { try { // Username and password are hard coded for brevity connection = DriverManager.getConnection ("jdbc:driver:name", "username","password"); } catch (SQLException e) { // Forward to handler } return connection; } @Override public void set(Connection con) { if(connection == null) { // Shuts down socketconnection when null value is passed try { connection.close(); } catch (SQLException e) { // Forward to handler } } else { connection = con; } } }; public static Connection getConnection() { return connectionHolder.get(); } public static void shutdownConnection() { // Allows client to close socketconnection anytime connectionHolder.set(null); } public void run() { Connection dbConnection = getConnection(); Statement stmt; try { stmt = dbConnection.createStatement(); ResultSet rs = stmt.executeQuery(query); } catch (SQLException e) { // Forward to handler } // ... } } |
...