开源连接池DBCP解析

来源:互联网 发布:算法交易 vwap 编辑:程序博客网 时间:2024/06/10 21:03

1.什么是DBCP?

DBCP是Apache软件基金组织下的开源连接池实现,使用DBCP数据源。Tomcat的连接池正是采用此连接池来实现的。该数据库连接池既可以与应用服务器整合使用,也可以由应用程序独立使用。

2.实现

程序需要的jar包:

•    Commons-dbcp.jar:连接池的实现

•    Commons-pool.jar:连接池实现的依赖库

3.硬编码实现DBCP对数据库的查询

//硬编码方式实现连接池@Testpublic void testDbcp() throws Exception{//DBCP核心实现类BasicDataSource dataSource=new BasicDataSource();//连接词参数的配置:初始化连接数、最大连接数dataSource.setUrl("jdbc:mysql://localhost:3306/basicjdbc?characterEncoding=utf-8");dataSource.setDriverClassName("com.mysql.jdbc.Driver");dataSource.setUsername("root");dataSource.setPassword(null);dataSource.setInitialSize(3);//初始化连接dataSource.setMaxActive(6);//最大连接数dataSource.setMaxIdle(3000);//最大空闲时间,单位是秒Connection conn=dataSource.getConnection();PreparedStatement pstmt=conn.prepareStatement("select * from myuser");ResultSet rs=pstmt.executeQuery();while(rs.next()){String username=rs.getString("username");String gender=rs.getString("gender");Integer id=rs.getInt("id");System.out.println(id+" ,"+username+" ,"+gender);}rs.close();pstmt.close();conn.close();}

结果:

3 ,Bryant3 ,男
4 ,Bryant4 ,男
5 ,Bryant5 ,男
6 ,Bryant6 ,男
7 ,Bryant7 ,男
8 ,Bryant8 ,男
9 ,Bryant9 ,男
11 ,Bryant11 ,男
12 ,Bryant12 ,男
13 ,Bryant13 ,男
14 ,Bryant14 ,男
15 ,Bryant15 ,男
16 ,Bryant16 ,男
17 ,Bryant17 ,男
18 ,Bryant18 ,男
19 ,Bryant19 ,男
20 ,Bryant20 ,男
21 ,null ,null3 ,Bryant3 ,男
解释:主要使用BasicDataSource类来实现连接池的配置,而剩下的查询和jdbc的查询没什么区别。

4.配置的方式实现DBCP对数据库的查询

导入的jar包和上面一样

dbcp.properties:

url=jdbc:mysql://localhost:3306/basicjdbc?characterEncoding=utf-8username=rootpassword=driverClassName=com.mysql.jdbc.DriverinitialSize=3maxActive=6maxIdle=3000
实现:

//配置方式实现连接池@Testpublic void testDbcp2() throws Exception{Properties prop=new Properties();FileInputStream fis=new FileInputStream("./src/dbcp.properties");          prop.load(fis);//根据prop的配置,直接创建数据源对象DataSource dataSource=BasicDataSourceFactory.createDataSource(prop);Connection conn=dataSource.getConnection();PreparedStatement pstmt=conn.prepareStatement("select * from myuser");ResultSet rs=pstmt.executeQuery();while(rs.next()){String username=rs.getString("username");String gender=rs.getString("gender");Integer id=rs.getInt("id");System.out.println(id+" ,"+username+" ,"+gender);}rs.close();pstmt.close();conn.close();}
结果:

解释:其实就是加载properties文件,通过读取properties文件的配置,来配置连接池,进而创建数据源对象。再获取连接操作等等。




0 0
原创粉丝点击