-
Notifications
You must be signed in to change notification settings - Fork 1
/
ConnManager.java
97 lines (86 loc) · 2.29 KB
/
ConnManager.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
85
86
87
88
89
90
91
92
93
94
95
96
97
package io.zhpooer.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 通过设施 conf/jdbc.conf, 管理数据库连接, 参数样式如下, debug=true|false,
* 如果debug为true, 运行h2临时数据库, 临时数据放在/tmp目录下
* driverClass=com.mysql.jdbc.Driver
* url=jdbc:mysql://localhost:3306/test user=root password=root
*
* @author poe
*
*/
public class ConnManager {
private static String url;
private static String user = "";
private static String password = "";
private static ConnManager instance;
private static String driverClass;
private ConnManager() {
}
static {
Properties p = new Properties();
try {
InputStream conf = ConnManager.class.getClassLoader().getResourceAsStream("jdbc.conf");
p.load(conf);
if (p.containsKey("debug")
&& Boolean.parseBoolean(p.getProperty(("debug")))) {
url = DbUtil.makeH2TempURL("sample");
driverClass = "org.h2.Driver";
} else {
driverClass = p.getProperty(("driverClass"));
url = p.getProperty("url");
user = p.getProperty("user");
password = p.getProperty("password");
}
Class.forName(driverClass);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
if (p.containsKey("sqlScript")) {
String scriptPath = ConnManager.class.getClassLoader()
.getResource(p.getProperty("sqlScript")).getPath();
DbUtil.execSQL(scriptPath, driverClass, url, user, password);
}
}
public static ConnManager getInstance() {
if (instance == null) {
synchronized (ConnManager.class) {
if (instance == null)
instance = new ConnManager();
}
}
return instance;
}
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public void release(Connection conn, Statement stmt, ResultSet rs) {
if (rs != null)
try {
rs.close();
} catch (SQLException e) {
} finally {
rs = null;
}
if (stmt != null)
try {
stmt.close();
} catch (SQLException e) {
} finally {
stmt = null;
}
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
} finally {
conn = null;
}
}
}