DBCP连接池
连接池存在的意义在于减少了服务端与数据库之间的直接交互。将常用的数据放在连接池里面。它与直接访问数据库的区别主要在于connection指向的位置不一样。
主要方法:
首先导入连个jar包:commons-dbcp-1.4.jar和commons-pool-1.6.jar
具体配备方法有两个:
1.BasicDataSource方式(硬编码)
public static DataSource getDataSourceWITHDBCP(){
BasicDataSource dbcp = new BasicDataSource();
dbcp.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dbcp.setUrl("jdbc:oracle:thin:@127.0.0.1:1521:ORCL");
dbcp.setUsername("scott");
dbcp.setPassword("tiger");
dbcp.setInitialSize(20);
dbcp.setMaxActive(10);
return dbcp;
}
//下面只是测试用的
public static void main(String[] args) {
Connection connection = null ;
PreparedStatement pstmt = null ;
try {
connection = getDataSourceWITHDBCP().getConnection();
String sql = "insert into student values(?,?,?,?)";
pstmt = connection.prepareStatement(sql);
pstmt.setInt(1,999);
pstmt.setString(2,"zs");
pstmt.setInt(3,999);
pstmt.setString(4,"G99");
int count = pstmt.executeUpdate();
if(count>0){
System.out.println("操作成功!!!!!!!");
}
} catch (SQLException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(pstmt!=null)pstmt.close();
if(connection!=null)connection.close();
}catch (SQLException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
}
做个对比,直接链接数据库 取connection的写法如下:
private static final String URL = "jdbc:oracle:thin:@localhost:1521:ORCL" ;
private static final String USERNAME = "scott" ;
private static final String PWD = "tiger" ;
Class.forName("oracle.jdbc.OracleDriver");//加载具体的驱动类
// b.与数据库建立连接
connection = DriverManager.getConnection(URL,USERNAME,PWD) ;
stmt = connection.createStatement() ;
2.BasicDataSourceFactory方式(配置文件的方法)
在项目src目录下建一个File(文件名为dbcpconfig.properties)内部配置如下:
driverClassName=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:ORCL
username=scott
password=tiger
initialSize=10
然后,java类调用它的写法如下:
public static DataSource getDataSourceWITHDBCPByProperties() throws Exception{
DataSource dbcp = null;
Properties props = new Properties();
InputStream input = new DBCPDemo().getClass().getClassLoader().getResourceAsStream("dbcpconfig.properties");
props.load( input );
dbcp = BasicDataSourceFactory.createDataSource(props);
return dbcp;
}
//验证如下:
public static void main(String[] args) throws Exception {
System.out.println(getDataSourceWITHDBCPByProperties().getConnection());
}
取到connection对象之后,后面的操作就跟jdbc一样。