1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| public static DBConnection getInstance() throws Exception {
if (DBConnection.dbconnection == null) {
//String path = "blabla";
String path = "blabla";
props.load(new FileInputStream(path));
//mettre en place le fichier de log la première fois
PropertyConfigurator.configure(props.getProperty("pathLog4j"));
setLog4j(Logger.getLogger("DBConnection.class"));
if(Logger.getLogger("DBConnection.class") == null)
System.out.println("La mise en place du système de log n'a pas fonctionné ");
else
log4j.log(Level.INFO,"Le système de log est mis en place: "+ getLog4j().getName());
log4j.log(Level.INFO, "pathLog4j: "+props.getProperty("pathLog4j"));
DBConnection.dbconnection = new DBConnection();
log4j.log(Level.INFO, "DBConnection.dbconnection = new DBConnection();");
}
return DBConnection.dbconnection;
}
public Connection getConnection() throws Exception {
if (DBConnection.dbconnection == null)
throw new Exception("Singleton non initialisé");
if (DBConnection.conn != null && !DBConnection.conn.isClosed())
{
return DBConnection.conn;
}
else
log4j.log(Level.INFO, "Connection == null");
try {
DBConnection.conn = getConnection3();
} catch (Exception ex) {
log4j.log(Level.FATAL, "Erreur lors du chargement du dataSource");
ex.printStackTrace();
throw new Exception("Erreur lors du chargement du dataSource");
}
return conn;
}
private static Connection getConnection3() throws Exception {
if (DBConnection.conn != null && !DBConnection.conn.isClosed())
{
return DBConnection.conn;
}
user = props.getProperty("user");
password = props.getProperty("password");
host = props.getProperty("host");
port = props.getProperty("port");
dbname = props.getProperty("dbname");
try {
String url = "jdbc:mysql://" + host +":"+port+ "/" + dbname;
log4j.log(Level.INFO, "url: "+ "jdbc:mysql://" + host +":"+port+ "/" + dbname);
Class.forName("com.mysql.jdbc.Driver").newInstance();
DBConnection.conn = DriverManager.getConnection(url, user, password);
log4j.log(Level.INFO, "Connection DB réussie");
} catch (Exception e) {
log4j.log(Level.FATAL, "Echec de la connection DB" + e);
}
return DBConnection.conn;
} |
Partager