public class java_数据库连接池 {
//1.定义变量
//管理数据连接池对象
private ComboPooledDataSource ds;
//2.构造方法
private java_数据库连接池() {
//对数据库连接池对象进行初始配置
ds = new ComboPooledDataSource();
try {
//设置驱动
ds.setDriverClass("com.mysql.cj.jdbc.Driver");
//设置用户
ds.setUser("root");
//设置密码
ds.setPassword("12345678");
//设置URL
ds.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=UTF8&useSSL=false");
//设置初始连接数 初始不能大于最大连接数
ds.setInitialPoolSize(5);
//设置最大连接数
ds.setMaxPoolSize(10);
//设置最小连接数
ds.setMinPoolSize(3);
//设置statement最大数量
ds.setMaxStatements(20);
//设置检查连接超时的时间 单位为毫秒
ds.setCheckoutTimeout(60000);
//检查闲置连接的周期时间 单位为秒
ds.setMaxIdleTime(10);
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 单例模式:
* 当全局对象只需要一个对象,保持全局对象的唯一性,达到资源共享;
* new了之后不释放,耗资源,需要手动置为null来释放
*/
/** 懒汉模式:用实例的时候才创建
* 优点:在不使用该实例时,不占用内存空间
* 缺点:多线程时,需要通过同步的手段达到实例唯一性,效率低
*/
private static java_数据库连接池 cmanager = null;
//获取当前类对象
public synchronized static java_数据库连接池 instance() {
if (cmanager == null) {
cmanager = new java_数据库连接池();
}
return cmanager;
}
/**
* 恶汉模式:
* 优点:多线程访问时,效率快
* 缺点:在不使用该实例时,占用内存空间
*/
// private static java_数据库连接池 manager = new java_数据库连接池();
// public static java_数据库连接池 instance() {
// return manager;
// }
//获取连接池中的连接对象
public Connection getConn() {
try {
return (Connection) this.ds.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public class Text {
public static void main(String[] args) {
java_数据库连接池 sc = java_数据库连接池.instance();
Connection connection = (Connection) sc.getConn();
try {
Statement statement = connection.createStatement();
statement.execute("insert into student values(8,'周帅',23)");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}