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 cn.xxx.jdbc.utils.C3P0Utils; // 自定义的连接池工具类
public class Demo {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
//通过工具类,从连接池中获取连接
conn = C3P0Utils.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();
}
}
}
}
}
C3P0Utils.java(连接池工具类):
package cn.xxx.jdbc.utils;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Utils {
// 根据配置文件,创建连接池对象。
private static ComboPooledDataSource dataSource = new ComboPooledDataSource("配置文件中的配置名"); // 空参数表示默认配置
public static DataSource getDataSource() {
return dataSource;
}
public static Connection getConnection() {
try {
return dataSource.getConnection(); // 从连接池中获取一个连接对象
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
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>