1
|
/*
|
2
|
* To change this license header, choose License Headers in Project Properties.
|
3
|
* To change this template file, choose Tools | Templates
|
4
|
* and open the template in the editor.
|
5
|
*/
|
6
|
package eu.dnetlib.usagestats.export;
|
7
|
|
8
|
/*
|
9
|
@author dpie
|
10
|
*/
|
11
|
import java.sql.Connection;
|
12
|
import java.sql.DriverManager;
|
13
|
import java.sql.SQLException;
|
14
|
import java.sql.Statement;
|
15
|
import java.util.Properties;
|
16
|
import org.apache.log4j.Logger;
|
17
|
|
18
|
public abstract class ConnectDB {
|
19
|
|
20
|
private static Connection DB_CONNECTION;
|
21
|
|
22
|
private static String dbURL;
|
23
|
private static String dbUsername;
|
24
|
private static String dbPassword;
|
25
|
private static String defaultDBSchema;
|
26
|
private final static Logger log = Logger.getLogger(ConnectDB.class);
|
27
|
|
28
|
static void init(Properties properties) throws ClassNotFoundException {
|
29
|
|
30
|
dbURL = properties.getProperty("Stats_db_Url");
|
31
|
dbUsername = properties.getProperty("Stats_db_User");
|
32
|
dbPassword = properties.getProperty("Stats_db_Pass");
|
33
|
defaultDBSchema = properties.getProperty("Stats_db_Schema");
|
34
|
|
35
|
Class.forName(properties.getProperty("Stats_db_Driver"));
|
36
|
}
|
37
|
|
38
|
public static Connection getConnection() throws SQLException {
|
39
|
if (DB_CONNECTION != null && !DB_CONNECTION.isClosed()) {
|
40
|
return DB_CONNECTION;
|
41
|
} else {
|
42
|
DB_CONNECTION = connect();
|
43
|
|
44
|
return DB_CONNECTION;
|
45
|
}
|
46
|
}
|
47
|
|
48
|
private static Connection connect() throws SQLException {
|
49
|
Connection connection = DriverManager.getConnection(dbURL, dbUsername, dbPassword);
|
50
|
Statement stmt = connection.createStatement();
|
51
|
String sqlSetSearchPath = "SET search_path TO " + defaultDBSchema + ";";
|
52
|
stmt.executeUpdate(sqlSetSearchPath);
|
53
|
stmt.close();
|
54
|
|
55
|
log.debug("Opened database successfully");
|
56
|
|
57
|
return connection;
|
58
|
}
|
59
|
|
60
|
}
|