一.使用C3P0连接池
- 拷贝jar包
- 拷贝和修改配置文件
- 修改JDBCUtil,让其获取连接的方式变成从C3P0连接池获取
- 创建一个ComboPooledDataSource对象(C3P0连接池对象)
- 调用连接池对象的getConnection()方法获取连接
- 连接使用完之后,调用连接对象的close()方法归还连接
/**
* 使用C3P0连接池获取连接对象
* 注意点:
* 1.配置文件的文件名只能叫做"c3p0-config.xml"
* 2.配置文件中的标签名和name属性值都是固定的
* 3.只能改标签体的内容
* 4.创建的连接池对象是ComboPooledDataSource对象
*/
public class JDBCUtil {
private static DataSource dataSource;
static {
//创建一个C3P0连接池的对象
dataSource = new ComboPooledDataSource();
}
/**
* 获取连接对象的方法
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception {
//获取连接,不再新创建了,而是从连接池对象中获取
return dataSource.getConnection();
}
/**
* 关闭conn和statement的方法
* @param conn
* @param stm
* @throws SQLException
*/
public static void close(Connection conn,Statement stm) throws SQLException {
close(conn,stm,null);
}
/**
* 关闭conn、stm、rst对象
* @param conn
* @param stm
* @param rst
*/
public static void close(Connection conn, Statement stm, ResultSet rst) throws SQLException {
if (rst != null) {
rst.close();
}
if(stm != null){
stm.close();
}
if (conn != null) {
conn.close();
}
}
}
二.使用Druid连接池
- 拷贝jar包
- 拷贝和修改配置文件
- 修改JDBCUtil工具类,让其获取连接的方式变成从Druid连接池获取
- 使用工厂类DruidDataSourceFactory创建连接池对象
- 调用连接池对象的getConnection()方法获取连接
- 连接使用完之后,调用连接对象的close()方法归还连接
/**
* 使用Druid连接池:从Druid;连接池中获取连接对象
* 连接池使用的步骤:
* 1.拷贝jar包
* 2.准备配置文件
* 3.创建连接池对象
* 4.使用连接池对象获取连接
* 5.调用连接的close()方法归还连接
*/
public class JDBCUtil {
private static DataSource dataSource;
static {
//1.创建Druid连接池对象
//读取druidconfig.properties配置文件
ClassLoader classLoader = JDBCUtil.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("druidconfig.properties");
Properties properties = new Properties();
try {
properties.load(is);
//使用工厂类创建
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接对象的方法
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception {
//获取连接,不再新创建了,而是从连接池对象中获取
return dataSource.getConnection();
}
/**
* 关闭conn和statement的方法
* @param conn
* @param stm
* @throws SQLException
*/
public static void close(Connection conn,Statement stm) throws SQLException {
close(conn,stm,null);
}
/**
* 关闭conn、stm、rst对象
* @param conn
* @param stm
* @param rst
*/
public static void close(Connection conn, Statement stm, ResultSet rst) throws SQLException {
if (rst != null) {
rst.close();
}
if(stm != null){
stm.close();
}
if (conn != null) {
conn.close();
}
}
}