1、第三方连接池
C3P0 Hibernate框架里面集成的就是C3p0
druid 阿里,最优
DBCP apache,Tomcat
1.1、C3P0
最简单方式:
(1)加载依赖
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
(2)通过c3p0获取数据库连接
//c3p0连接池
@Test
public void demo01() throws PropertyVetoException, SQLException {
ComboPooledDataSource cpds=new ComboPooledDataSource();
cpds.setDriverClass("com.mysql.cj.jdbc.Driver");
cpds.setJdbcUrl("jdbc:mysql://localhost:3306/db02");
cpds.setUser("root");
cpds.setPassword("Root123456");
Connection connection=cpds.getConnection();
System.out.println(connection);
}
最优方式:
(1)加载依赖
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
(2)创建配置文件 c3p0-config.xml
resources下
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">url=jdbc:mysql://localhost:3306/db02</property>
<property name="user">root</property>
<property name="password">Root123456</property>
<property name="initialPoolSize">5</property>
</default-config>
</c3p0-config>
(3)编写C3p0工具类
package com.ww.jdbc_demo_01.util;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
public class C3P0Util {
private static DataSource dataSource;
static {
dataSource= new ComboPooledDataSource();
}
public static DataSource getDataSource(){
return dataSource;
}
}
1.2、Druid
普通用法
(1)导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.16</version>
</dependency>
(2)创建连接
@Test
public void demo01() throws SQLException {
DruidDataSource dataSource=new DruidDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/db02");
dataSource.setUsername("root");
dataSource.setPassword("Root123456");
dataSource.setInitialSize(5);
Connection connection =dataSource.getConnection();
System.out.println(connection);
}
常用方法
(1)导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.16</version>
</dependency>
(2)创建配置文件jdbc.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db02
username=root
password=Root123456
(3)编写工具类
package com.ww.jdbc_demo_01.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;
import java.util.ResourceBundle;
public class DruidUtil {
private static DataSource dataSource;
static{
try {
Properties properties=new Properties();
InputStream in=DruidUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(in);
dataSource= DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static DataSource getDataSource(){
return dataSource;
}
}