C3P0 jar包下载地址:https://repo1.maven.org/maven2/com/mchange/c3p0
C3P0 配置文件c3p0-config.xml
<c3p0-config>
<!-- 使用默认的配置读取连接池对象 -->
<!-- 连接池的名称-->
<named-config name="C3P0pool">
<!-- 连接参数 -->
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/db01</property>
<property name="user">root</property>
<property name="password">123456</property>
<!-- 连接池参数 -->
<!-- 初始连接数 -->
<property name="initialPoolSize">5</property>
<!-- 最大连接数 -->
<property name="maxPoolSize">50</property>
<!-- 超时时间 -->
<property name="checkoutTimeout">3000</property>
</named-config>
</c3p0-config>
语法:
public class c3p0_test2 {
public static void main(String[] args) throws SQLException {
// 在libs目录下加入c3p0包
// 在src目录下加入配置文件 c3p0-config.xml
// 这里参数填写在配置文件里配置的名字 <named-config name="C3P0pool">
ComboPooledDataSource c3P0pool = new ComboPooledDataSource("C3P0pool");
//连接
Connection connection = c3P0pool.getConnection();
//数据库查询
String sql = "select * from admin";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
String user = resultSet.getString(1);
String password = resultSet.getString(2);
System.out.println("user = :" + user);
System.out.println("password = :" + password);
}
//关闭资源
resultSet.close();
preparedStatement.close();
connection.close();
}
}