开发者学堂课程【 JDBC 数据库开发进阶:c3p0 连接池的基本使用方式】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/32/detail/685
c3p0 连接池的基本使用方式
内容介绍
1.c3p0 简介
2.c3p0 的使用范例
1.c3p0 简介
是开元免费的连接池,比较受欢迎
2.c3p0 的使用范例:
package cn.bl.v4_DataSource.c3p0;
import java.sql.SQLException;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class Demo1 {
/**
* 方式1:使用纯Java方式
* @throws Exception
*/
@Test
public void test1() throws Exception {
ComboPooledDataSource source = new ComboPooledDataSource();
source.setDriverClass("com.mysql.jdbc.Driver");
source.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/aa?useUnicode=true&characterEncoding=utf-8");
source.setUser("root");
source.setPassword("000");
//获取链接 System.out.println(source.getConnection());
/*输出如下信息(除了最后一行,前面的其实都是自动输出的基本信息): 九月 23, 2018 11:40:45 上午 com.mchange.v2.log.MLog
信息: MLog clients using java 1.4+ standard logging.
九月 23, 2018 11:40:45 上午 com.mchange.v2.c3p0.C3P0Registry banner
}
@Test
public void test2() throws SQLException {
//1.空参--默认配置 ComboPooledDataSource ds = new ComboPooledDataSource();
//2.带参--指定名称的配置 //ComboPooledDataSource ds = new ComboPooledDataSource("BarryLee
System.out.println(ds.getConnection());
//输出的信息类似test1
}
/*
* 测试c3p0工具类
*/
@Test
public void testUtil() {
System.err.println(C3P0Utils.getConnection());
}
}
package cn.bl.v4_DataSource.c3p0;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Utils {
private C3P0Utils() {}
private static ComboPooledDataSource ds = null;
private static ThreadLocaltLocal = new ThreadLocal<>();
static {
ds = new ComboPooledDataSource();//读取默认配置文件
}
public static DataSource getDataSource() {
return ds;
}
public static Connection getConnection() {
Connection con = tLocal.get();
if(con==null) {
try {
con = ds.getConnection();
tLocal.set(con);
} catch (SQLException e) {
e.printStackTrace();
}
}
return con;
}
}