C3P0
开源免费的连接池,使用的开源项目有Spring,Hibernate等。需要导入jar包,配置文件为c3p0-config.xml
提供核心工具类:ComboPooledDataSource ,如果使用连接池必须创建该类的实例对象。 构造方法中放入"配置命名"。
编写工具类
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Utils {
private static DataSource dataSource = new ComboPooledDataSource("Cai");
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
检测
public class Test_C3P0 {
@Test
public void test123(){
Statement st = null;
PreparedStatement pstmt = null;
Connection conn =null;
//不抽取工具类时需要新建如下对象中的一个
//DataSource dataSource = new ComboPooledDataSource();
//DataSource dataSource = new ComboPooledDataSource("Cai");
try {
conn=C3P0Utils.getConnection();
st = conn.createStatement(); //调用了conn的方法 需要在实现类中重写方法
//添加:
int r = st.executeUpdate("insert into product values(null,'王1',200,null,3)");
System.out.println(r);
} catch (Exception e) {
e.printStackTrace();
}finally{
JdbcUtils.release(null, pstmt, conn);
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
DBCP连接池
需要导入jar包,配置文件后缀properties,不支持XML。创建连接的时候比较麻烦。
工具类
public class DBCPUtils {
private static DataSource dataSource;
static{
try {
//1 加载找到配置文件
InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
//2 加载输入流
Properties props = new Properties();
props.load(is);
//3 创建数据源
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}