c3p0:传统的数据库连接池,稳定,速度一般
Druid:阿里出的一款,稳定,速度快
注:在数据库技术中断掉连接并不是真的断掉与数据库的连接,而是将使用的Connection对象放回数据连接池中等待下一次取出使用,Connection对象一直都保持和数据库连接。
c3p0的使用:
- 引入c3p0的jar包,编译为依赖库
- 将c3p0-config.xml配置文件配置好并引入到src目录下
ComboPooledDataSource cpds = new ComboPooledDataSource(c3p0-config.xml中配置的数据源名);
Connection connection = cpds.getConnection();//创建连接
connection.close();//关闭连接
c3p0-config.xml:
<c3p0-config>
<!-- 连接池数据源名字 -->
<named-config name="hello">
<!-- 驱动类 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<!-- url-->
<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/要连接的数据库名?rewriteBatchedStatements=true</property>
<!-- 用户名 -->
<property name="user">root</property>
<!-- 密码 -->
<property name="password">root</property>
<!-- 每次增长的连接数-->
<property name="acquireIncrement">5</property>
<!-- 初始的连接数 -->
<property name="initialPoolSize">10</property>
<!-- 最小连接数 -->
<property name="minPoolSize">5</property>
<!-- 最大连接数 -->
<property name="maxPoolSize">50</property>
<!-- 可连接的最多的命令对象数 -->
<property name="maxStatements">5</property>
<!-- 每个连接对象可连接的最多的命令对象数 -->
<property name="maxStatementsPerConnection">2</property>
</named-config>
</c3p0-config>
Druid的使用:
- 引入Druid的jar包,编译为依赖库
- 将druid.properties配置文件配置好并引入到src目录下
Properties properties = new Properties();
properties.load(new FileInputStream("src\\druid.properties"));
DataSource ds = DruidDataSourceFactory.createDataSource(properties);//创建连接
Connection connection = ds.getConnection();//创建连接
connection.close();//关闭连接
druid.properties:
#key=value,8.0版本以上使用com.mysql.cj.jdbc.Driver
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库?rewriteBatchedStatements=true
#url=jdbc:mysql://localhost:3306/girls
username=root
password=root
#initial connection Size,初始化连接数
initialSize=10
#min idle connecton size,最小连接数
minIdle=5
#max active connection size,最大连接数
maxActive=20
#max wait time (5000 mil seconds),最大等待连接时间
maxWait=5000