1
|
package eu.dnetlib.utils.sql;
|
2
|
|
3
|
import java.sql.Connection;
|
4
|
import java.sql.DriverManager;
|
5
|
|
6
|
/**
|
7
|
* This factory class is used for retrieving a singleton JDBC connection.
|
8
|
* @author thanos@di.uoa.gr
|
9
|
*
|
10
|
*/
|
11
|
public class ConnectionFactory {
|
12
|
private String driver;
|
13
|
private String url;
|
14
|
private Connection connection;
|
15
|
|
16
|
/**
|
17
|
* Set the driver.
|
18
|
* @param driver the new JDBC driver that this factory will use
|
19
|
*/
|
20
|
public void setDriver(String driver) {
|
21
|
this.driver = driver;
|
22
|
}
|
23
|
|
24
|
/**
|
25
|
* Set the URL.
|
26
|
* @param url the new URL that this factory will connect to
|
27
|
*/
|
28
|
public void setUrl(String url) {
|
29
|
this.url = url;
|
30
|
}
|
31
|
|
32
|
/**
|
33
|
* Get the connection.
|
34
|
* @return the JDBC connection created by this connection factory
|
35
|
*/
|
36
|
public Connection getConnection() {
|
37
|
return connection;
|
38
|
}
|
39
|
|
40
|
/**
|
41
|
* Open JDBC connection to the specified URL using the specified JDBC driver (used for Spring initialization).
|
42
|
* @throws ConnectionFactoryException if any errors occur
|
43
|
*/
|
44
|
public void init() throws ConnectionFactoryException {
|
45
|
try {
|
46
|
Class.forName(driver).newInstance();
|
47
|
connection = DriverManager.getConnection(url);
|
48
|
} catch (Exception e) {
|
49
|
throw new ConnectionFactoryException("error connecting to " + url + " using JDBC driver " + driver, e);
|
50
|
}
|
51
|
}
|
52
|
|
53
|
/**
|
54
|
* Close JDBC connection (used for Spring finalization).
|
55
|
* @throws ConnectionFactoryException if any errors occur
|
56
|
*/
|
57
|
public void destroy() throws ConnectionFactoryException {
|
58
|
try {
|
59
|
connection.close();
|
60
|
} catch (Exception e) {
|
61
|
throw new ConnectionFactoryException("error closing connection", e);
|
62
|
}
|
63
|
}
|
64
|
}
|