数据库连接池和JDBCTemplate

数据库连接池

定义:本质就是一个容器(集合),存放数据库连接的容器
    当系统初始化好后,容器就被创建,容易中会申请一些连接对象,当用户来访问数据库的时候,从容器中获取连接对象,用户访问完之后,将连接对象归还给容器

优点:节约资源、用户访问高效

实现
    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操作
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值