创新实训——数据库连接池的实现(三)

   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);
}

猜你喜欢

转载自blog.csdn.net/UnLongChemin/article/details/82110742