1. 创建一个名称为JDBC_C3P0的Java工程
2. 添加c3p0的jar
3. 代码中设置连接数据库的信息
4. 在配置文件c3p0-config.xml(必须叫这个名字, 并且放置在src目录下, 因为这样可以自动加载)中设置连接数据库的信息
5. c3p0-config.xml配置详情
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!-- default-config 默认的配置 -->
<default-config>
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://192.168.25.130:3306/studyjdbc?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai</property>
<property name="user">root</property>
<property name="password">lyw123456</property>
<!-- 初始化连接池数量 -->
<property name="initialPoolSize">10</property>
<!-- 数据库连接最大空闲时间 -->
<property name="maxIdleTime">30</property>
<!-- 池子最大连接数 -->
<property name="maxPoolSize">100</property>
<!-- 池子最小连接数 -->
<property name="minPoolSize">10</property>
<!-- 最大Statements对象数 -->
<property name="maxStatements">200</property>
</default-config>
</c3p0-config>
6. 使用c3p0-config.xml配置文件建立数据库连接
7. 使用c3p0数据库连接池代码
package com.lywgames.myjdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class MyJDBC {
public static void main(String[] args) {
c3p0UseConfig();
}
public static void c3p0() {
Connection conn = null;
PreparedStatement ps = null;
try {
//1. 创建datasource
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//2. 设置连接数据库的信息
dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://192.168.25.130:3306/studyjdbc?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai");
dataSource.setUser("root");
dataSource.setPassword("lyw123456");
//3. 得到连接对象
conn = dataSource.getConnection();
ps = conn.prepareStatement("insert into user values(null,?,?,?)");
ps.setString(1, "machao");
ps.setString(2, "123456");
ps.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(ps != null){
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
ps = null;
}
}
}
public static void c3p0UseConfig() {
Connection conn = null;
PreparedStatement ps = null;
try {
//1. 创建datasource通过类加载器查找c3p0-config.xml
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//2. 得到连接对象
conn = dataSource.getConnection();
ps = conn.prepareStatement("insert into user values(null,?,?,?)");
ps.setString(1, "pangjuan");
ps.setString(2, "123456");
ps.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(ps != null){
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
ps = null;
}
}
}
}