JDBC连接池(三)DBCP连接池
在前面的随笔中提到 了 1.JDBC自定义连接池 2. C3P0连接池
今天将介绍DBCP连接池
第一步要导入jar包 (注意:mysql和mysql 驱动的版本问题 ,驱动过低会造成下图异常)
创建db.properties 配置文件
DBCPUtils.java 文件
package com.study.jdbc.Utils; import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSourceFactory; public class DBCPUtils { private static DataSource dataSource;
static{ try {
InputStream is=DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties props=new Properties();
props.load(is);
//创建数据源
System.out.println(props.getProperty("driver"));
dataSource=BasicDataSourceFactory.createDataSource(props);
System.out.println(dataSource);
} catch (Exception e) {
throw new RuntimeException(e);
} }
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection(){ try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
TestDBCP.java
package cn.itheima.jdbc.test; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import org.junit.Test; import cn.itheima.jdbc.utils.DBCPUtils; public class TestDBCP { @Test
public void test1(){
Connection conn=null;
PreparedStatement pstm=null;
ResultSet rs=null;
try {
conn=DBCPUtils.getConnection();
String sql="select * from user";
pstm=conn.prepareStatement(sql);
rs=pstm.executeQuery();
while(rs.next()){
System.out.print(" userId ="+rs.getObject("userId")+" ");
System.out.println(" userName ="+rs.getObject("userName")); }
} catch (Exception e) {
throw new RuntimeException(e);
} } public static void main(String[] args) {
Connection conn=null;
PreparedStatement pstm=null;
ResultSet rs=null;
try {
conn=DBCPUtils.getConnection();
String sql="select * from user";
pstm=conn.prepareStatement(sql);
rs=pstm.executeQuery();
while(rs.next()){
System.out.print(" userId ="+rs.getObject("userId")+" ");
System.out.println(" userName ="+rs.getObject("userName")); }
} catch (Exception e) {
throw new RuntimeException(e);
} }
}