Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package database;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.Properties;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class DatabaseConnection {
- private static final ThreadLocal<Connection> con = new ThreadLocalConnection();
- private final static Logger log = LoggerFactory.getLogger(DatabaseConnection.class);
- private static Properties props = null;
- public static Connection getConnection() {
- if (props == null) {
- throw new RuntimeException("DatabaseConnection not initialized");
- }
- Connection conn = con.get();
- try {
- if (conn.isValid(1)) {
- return conn;
- }
- } catch (SQLException sqle) {
- log.info("Lost connection to database, reconnecting...", sqle);
- try {
- conn.close();
- } catch (SQLException sqle2) {
- log.warn("Unable to close connection with database after losing connection", sqle2);
- }
- }
- ThreadLocalConnection.allConnections.remove(conn);
- con.remove();
- return con.get();
- }
- public static boolean isInitialized() {
- return props != null;
- }
- public static void setProps(Properties aProps) {
- props = aProps;
- }
- public static void cleanup(PreparedStatement ps, ResultSet rs) {
- if (rs != null) {
- try {
- rs.close();
- } catch (SQLException ex) {
- ex.printStackTrace();
- }
- }
- if (ps != null) {
- try {
- ps.close();
- } catch (SQLException ex) {
- ex.printStackTrace();
- }
- }
- }
- public static void closeAll() throws SQLException {
- for (Connection cons : ThreadLocalConnection.allConnections) {
- cons.close();
- }
- }
- private static class ThreadLocalConnection extends ThreadLocal<Connection> {
- public static Collection<Connection> allConnections = new ArrayList<>();
- @Override
- protected Connection initialValue() {
- String driver = props.getProperty("driver");
- String url = props.getProperty("url");
- String user = props.getProperty("user");
- String password = props.getProperty("password");
- try {
- Class.forName(driver); // Touch the mysql driver.
- } catch (ClassNotFoundException e) {
- log.error("ERROR", e);
- }
- try {
- Connection con = DriverManager.getConnection(url, user, password);
- allConnections.add(con);
- return con;
- } catch (SQLException e) {
- log.error("ERROR", e);
- return null;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement