在pom.xsl文件中添加
<dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency>
并且刷新装载
在resources中添加xml文件
<c3p0-config> <!-- comboPooledDataSource -->
<named-config name="webApp">
<!-- 配置连接信息 -->
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://192.168.153.149:3306/pet?characterEncoding=utf8</property>
<!-- 初始化时的数量 -->
<property name="password">root</property>
<property name="user">root</property>
<property name="initialPoolSize">15</property>
<!--一次要多少-->
<property name="acquireIncrement">10</property>
<!-- [10,20] -->
<!-- 池子中最小的连接数量 -->
<property name="minPoolSize">10</property>
<!-- 池子中最大的连接数量 -->
<property name="maxPoolSize">20</property>
<!-- 最大的statement的数量 -->
<property name="maxStatements">5</property>
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>
创建一个untils文件夹在中添加一个Jdbcuntil.java
package nj.zb.kb22.utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcUtil {
private static DataSource dataSource = null;
static {
dataSource=new ComboPooledDataSource("webApp");
}
public static Connection getConnection(){
Connection connection =null;
try {
connection= dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return connection;
}
public static void main(String[] args) {
DataSource dataSource1 = JdbcUtil.dataSource;
System.out.println(dataSource1);
Connection connection = JdbcUtil.getConnection();
System.out.println(connection);
PreparedStatement preparedStatement =null;
try {
preparedStatement = connection.prepareStatement("select * from dog");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getInt("id")+""+resultSet.getString("strain"));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
JdbcUtil.release(connection);
}
}
public static void release(Connection connection){
if (connection!=null) {
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
连接设置
public Connection getConnection(){
return JdbcUtil.getConnection();
}
文章描述了如何在pom.xml文件中添加c3p0依赖,并在resources目录下配置c3p0的XML设置,包括数据库连接信息和池参数。接着,创建了一个JdbcUtil工具类用于获取和释放数据库连接,展示了在Java代码中使用C3P0连接池的示例。
4015






