数据库连接池
定义:本质就是一个容器(集合),存放数据库连接的容器
当系统初始化好后,容器就被创建,容易中会申请一些连接对象,当用户来访问数据库的时候,从容器中获取连接对象,用户访问完之后,将连接对象归还给容器
优点:节约资源、用户访问高效
实现
1、标准接口:DataSource()
2、具体方法:获取连接:getConnection();归还连接:close()
3、连接池的实现:一般由数据库厂商完成
c3p0、druid
具体实现一个JDBCUtils的工具类(基于druid)
public class JDBCUtils {
//1、定义成员变量DataSource
private static DataSource ds;
//设置静态代码块,加载配置文件
static {
try {
Properties properties = new Properties();
properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//获取DataSource
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//释放资源
public static void close(Statement stat, Connection connection){
if (stat != null){
try {
stat.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(ResultSet resultSet, Statement stat, Connection connection){
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stat != null){
try {
stat.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
//获取连接池的方法
public static DataSource getDs(){
return ds;
}
}
JDBCTemplate
Spring框架对JDBC的简单封装,提供了JDBCTemplate对象简化了JDBC的开发
实现:
1、导入jar包
2、创建JDBCTemplate对象,依赖于DataSource数据源
JdbcTemplate template = new JdbcTemplate(ds);
3、调用JdbcTemplate方法完成CRUD操作