学习数据库连接池
使用到的包有c3p0和mysql-connector-java。
1、不使用xml配置文件
`
public static void main(String[] args) {
try {
//创建c3p0
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//加载驱动
dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/bank?useUnicode=true&characterEncoding=UTF-8");
dataSource.setUser("root");
dataSource.setPassword("root");
//设置初始化的链接个数
dataSource.setInitialPoolSize(20);
//设置最大连接数
dataSource.setMaxPoolSize(40);
//当链接对象不够时,再次申请过的个数
dataSource.setAcquireIncrement(5);
//设置最小连接数,当仅剩x个连接时,再次申请连接
dataSource.setMinPoolSize(2);
Connection connection = dataSource.getConnection();
System.out.println(connection);
} catch (PropertyVetoException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
`
2、使用xml配置文件
命名xml配置文件c3p0-config
xml内容:
`
<property name="user">root</property>
<property name="password">root</property>
<property name="driveClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/bank?useUnicode=true&characterEncoding=UTF-8</property>
<property name="AcquireIncrement">5</property>
<property name="InitialPoolSize">20</property>
<property name="MinPoolSize">2</property>
<property name="MaxPoolSize">40</property>
</named-config>
`

main方法里面:
`
public static void main(String[] args) {
try {
//创建c3p0
ComboPooledDataSource dataSource = new ComboPooledDataSource("testc3p0");
Connection connection = dataSource.getConnection();
System.out.println(connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
`
3、使用DBUtils小工具