-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathConnectorPool.java
executable file
·85 lines (73 loc) · 2.45 KB
/
ConnectorPool.java
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package database;
import java.sql.Connection;
import java.io.PrintStream;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;
public class ConnectorPool implements IConnector{
private String driverName;
private String fullPath;
private String user;
private String password;
PoolingDataSource poolDataSource;
private PrintStream outError;
public void setOutError(PrintStream out){
this.outError=out;
}
private void outError(Object information){
PrintStream currentOut=(this.outError==null)?System.out: this.outError;
currentOut.print("ConnectionPool");
currentOut.print(" ERROR ");
currentOut.println(information);
}
/** ñîçäàòü îáúåêò, êîòîðûé ñîäåðæèò POOL ñîåäèíåíèé ñ áàçîé äàííûõ
* @param driverName - èìÿ äðàéâåðà äëÿ ñîåäèíåíèÿ ñ JDBC
* @param fullPath - ïîëíûé URL ê áàçå äàííûõ
* @param userName - User Name
* @param password - Password
* @throws Exception - åñëè ïðîèçîøëà êàêàÿ-ëèáî îøèáêà âî âðåìÿ ïîïûòêè ñîåäèíåíèÿ ñ áàçîé äàííûõ
* */
public ConnectorPool(String driverName, String fullPath, String userName, String password) throws Exception {
this.driverName=driverName;
this.fullPath=fullPath;
this.user=userName;
this.password=password;
if(initPool()==false){
throw new Exception("init Error");
}
}
private boolean initPool() throws ClassNotFoundException {
Class.forName(driverName);
String connectionString = fullPath;
GenericObjectPool connectionPool = new GenericObjectPool(null);
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectionString, user, password);
new PoolableConnectionFactory(connectionFactory,
connectionPool,
null,
null,
false,
false);
poolDataSource= new PoolingDataSource(connectionPool);
return true;
}
@Override
public Connection getConnection() {
try{
return poolDataSource.getConnection();
}catch(Exception ex){
outError("getConnection Exception:"+ex.getMessage());
return null;
}
}
@Override
public Connection getConnection(String user, String password){
try{
return poolDataSource.getConnection(user,password);
}catch(Exception ex){
outError("getConnection Exception:"+ex.getMessage());
return null;
}
}
}