C3P0数据库连接池配置,项目启动时初始化(servlet)

来源:互联网 发布:产品数据管理软件 编辑:程序博客网 时间:2024/06/05 21:56

java配置:

  public static ComboPooledDataSource dataSource;
 
/**
* 从连接池中获取连接
* @return
* @throws SQLException 
*/
public static Connection getConnection(){
Connection con = null;

try {
con = dataSource.getConnection();

} catch (SQLException e) {
e.printStackTrace();
}

return con;
}
/**
* 根据配置信息初始化连接池
* @param dataConf
*/
public static void initDataSource(){
dataSource = new ComboPooledDataSource();
    dataSource.setJdbcUrl(url);
try {
dataSource.setDriverClass(name);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setInitialPoolSize(5);
dataSource.setMaxPoolSize(15);
dataSource.setMaxIdleTime(1000);
System.out.println("连接池初始化成功!");

}

项目启动时初始化连接池   ( loadOnStartup=2  启动时的级别)

新建 initC3P0 Servlet

@WebServlet(description = "C3P0数据库连接池初始化",urlPatterns={"/InitC3P0Conf"},loadOnStartup=2 )
public class InitC3P0 extends HttpServlet{


private static final long serialVersionUID = 1L;

/**
* C3P0数据库连接池初始化
*/

@Override
public void init() throws ServletException {
C3P0Utils.initDataSource();
}


}