4.实现数据库连接管理的接口类
ConnectionManager负责提供获取连接的接口,使用单例模式。
public class ConnectionManager {
private static ConnectionManager INSTANCE;
private static ConnectionPool connectionPool;
public static ConnectionManager inst() {
if (INSTANCE == null) {
synchronized (ConnectionManager.class) {
if (INSTANCE == null) {
INSTANCE = new ConnectionManager();
INSTANCE.init();
}
}
}
return INSTANCE;
}
public void init(){
connectionPool=new ConnectionPool();
}
public RealConnection getRealConnection(){
return connectionPool.get();
}
}
使用的时候要保证ResultSet和RealPreparedStatement的正常关闭。
RealConnection conn = ConnectionManager.inst().getRealConnection();
String sql;
RealPreparedStatement statement=null;
ResultSet resultSet=null;
try {
sql = "...";
statement = conn.prepareStatement(sql);
resultSet = statement.executeQuery();
...
} catch (SQLException e) {
} finally {
ToolUtil.closeQuietly(resultSet,statement);
}