我感觉DBCP用起来比c3p0复杂一点,但是DBCP也占有一定的使用份额,所以我也推荐学一下
建立DBCP连接池的步骤:
1.导入jar包(DBCP需要的jar包比较多,要四个)
操作数据库的jar包就不说了,上篇博客说了
commons-dbcp2-2.5.0.jar 和 commons-pool2-2.6.0.jar 和 commons-logging-1.2.jar
2.配置DBCP文件,文件是.properties,这个不一定找的到这个后缀文件,就创建File就好了
########DBCP配置文件##########
#这个配置文件必须使用utf-8的编码形式,不然注释会出现乱码
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/usta
username=root
password=root
#初试连接数
initialSize=30
#最大活跃数
maxTotal=30
maxIdle=10
minIdle=5
#最长等待时间(毫秒)
maxWaitMillis=1000
#程序中的连接不使用后是否被连接池回收
#removeAbandoned=true
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
#连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒)
removeAbandonedTimeout=1
3.写一个DBCP的工具类
package com.xx.train.bdqn.jdbc.utils;
//创建DBCP工具类
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
public class DBCPUtils {
private static DataSource dataSource;
static {
try {
// 1.加载找到properties文件
InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
// 2.加载输入流
Properties props = new Properties();
props.load(is);
// 3.创建数据源
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static DataSource getDataSource() {
return dataSource;
}
public static Connection getConnection() throws Exception {
return dataSource.getConnection();
}
}
4.写一个测试类,插入一条数据
package com.xx.train.bdqn.jdbc.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class AddDBCP {
public void updateuser() throws Exception {
Connection con = null;
PreparedStatement pstmt =null;
con = DBCPUtils.getConnection();
String sql = "insert into user value(null,?,?)";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, "张三");
pstmt.setString(2, "123");
int n = pstmt.executeUpdate();
if(n>0) {
System.out.println("更新成功");
}else {
System.out.println("更新失败");
}
}
}
5.调用测试类
package com.xx.train.bdqn.jdbc.test;
import com.xx.train.bdqn.jdbc.utils.AddDBCP;
public class TestDBCP {
public static void main(String[] args) throws Exception {
AddDBCP u = new AddDBCP();
u.updateuser();
}
}