if(Connection_Db.isValid(Connection_Db.getInstance())==false) { connect=false; throw new SQLException(); } else { connect=true; commHandler.logger.info("Connection Data Base Sucess"); }
public static boolean isValid(Connection connection){ if(connection==null){ return false; } ResultSet ping = null; try{ if(connection.isClosed()){return false;} ping = connection.createStatement().executeQuery("SELECT 1"); return ping.next(); }catch(SQLException sqle){ return false; } finally{ if(ping!=null){try{ping.close();}catch(Exception e){}} } }
public class Connection_Db{ /** * URL de connection */ private static String url = "jdbc:postgresql://localhost:543/test"; /** * Nom du user */ private static String user = "postgres"; /** * Mot de passe du user */ private static String passwd = "toto"; /** * Objet Connection */ private static Connection connect; /** * Méthode qui va nous retourner notre instance * et la créer si elle n'existe pas... * @return * @throws SQLException */ public static Connection getInstance() throws SQLException{ if(connect == null){ connect = DriverManager.getConnection(url, user, passwd); } else { if(!isValid(connect)) { connect.close(); connect = DriverManager.getConnection(url, user, passwd); } } return connect; } public static boolean isValid(Connection connection){ if(connection==null){ return false; } ResultSet ping = null; try{ if(connection.isClosed()){return false;} ping = connection.createStatement().executeQuery("SELECT 1"); return ping.next(); }catch(SQLException sqle){ return false; } finally{ if(ping!=null){try{ping.close();}catch(Exception e){}} } } } }