数据连接池的主要概念就是相当于一的超大的水杯喝水,而每次举起杯子又很麻烦,所以就连上吸管去喝,又不断开,保持一定的连接数。

我的想法是先写一个通用的连接池连接,然后再根据增删改查的相关,再在小模块里面使用不同的sql语句完成相应的操作,最后返还数据池。

说的直白点就是登录数据库的操作简化成类模块。

先写一个通用的模板。

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mysql.cj.jdbc.Driver;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class C3P0Utils {
// 静态数据源实例
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

static {
try {
// 配置C3P0连接池
dataSource.setDriverClass(Driver.class.getName());
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb1");
dataSource.setUser("root");
dataSource.setPassword("123456");
dataSource.setInitialPoolSize(10);
dataSource.setMaxPoolSize(20);
} catch (Exception e) {
e.printStackTrace();
}
}

// 获取数据库连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}

@Test
public void t1() {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
Connection conn = null;

try {
// 获取连接
conn = C3P0Utils.getConnection();
String sql = "select * from user";
preparedStatement = conn.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();

// 处理结果集
while (resultSet.next()) {
System.out.println("User ID: " + resultSet.getInt("id") + ", User Name: " + resultSet.getString("name"));
}

} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
if (conn != null) conn.close(); // 将连接返回给连接池
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

然后再在自己的需求里面执行不同的增删改查语句即可