MySql驱动(jar包)下载:https://pan.baidu.com/s/19BYnGbO3l5MOOic5K4Ooaw 密码:mwoh
c3p0连接池下载(jar包,和xml配置文件):https://pan.baidu.com/s/18DodkCHFi07MQdTGACQU7Q 密码:m6fq
Demo.java:
package cn.xxx.jdbc.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class Demo {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
// 1.创建连接池对象
ComboPooledDataSource dataSource = new ComboPooledDataSource(); // 根据默认配置创建连接池对象
// ComboPooledDataSource dataSource = new ComboPooledDataSource("配置文件中的配置名"); //根据有名称的配置创建
try {
// 2.从连接池中获取连接
conn = dataSource.getConnection();
String sql = "insert into tbl_user values(null,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "zhangsan");
pstmt.setString(2, "123");
int rows = pstmt.executeUpdate();
if (rows > 0) {
System.out.println("添加成功!");
} else {
System.out.println("添加失败!");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally { // 释放资源;并不是真正释放,而是将连接归还到连接池中
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
src/c3p0-config.xml(c3p0连接池的配置文件,放在src目录下):
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config> <!-- 默认配置 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///数据库名</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
<named-config name="配置文件中的配置名"> <!-- 带配置名的配置 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///数据库名</property>
<property name="user">root</property>
<property name="password">root</property>
</named-config>
</c3p0-config>