数据库连接池(C3P0、Druid、Hikari)、Spring JDBC

数据库连接池

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

好处:

  1. 节约资源

  2. 用户访问高效

  3. 标准接口:DataSource javax.sql包下的

    1. 方法:
      • 获取连接:getConnection()
      • 归还连接:Connection.close()。如果连接对象Connection是从连接池中获取的,那么调用Connection.close()方法,则不会再关闭连接了。而是归还连接
    2. 一般我们不去实现它,有数据库厂商来实现
      1. C3P0:数据库连接池技术
      2. Druid:数据库连接池实现技术,由阿里巴巴提供的
/* C3P0:数据库连接池技术
https://sourceforge.net/projects/c3p0/files/latest/download?source=files
	* 步骤:
		1. 导入jar包 (两个) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar ,
		2. 定义配置文件:
			* 名称: c3p0.properties 或者 c3p0-config.xml
			* 路径:直接将文件放在src目录下即可。
		3. 创建核心对象 数据库连接池对象 ComboPooledDataSource
		4. 获取连接: getConnection
*/
public class C3p0Demo {
    public static void main(String[] args) throws SQLException {
        //1.创建数据库连接池对象
        DataSource dataSource = new ComboPooledDataSource();
        //2. 获取连接对象
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("select * from student2");
        ResultSet resultSet = preparedStatement.executeQuery();
        List<Student> list = new ArrayList<>();
        while(resultSet.next()){
            Student student = new Student();
            student.setId(resultSet.getInt(1));
            student.setName(resultSet.getString(2));
            student.setAge(resultSet.getInt(3));
            student.setSex(resultSet.getString(4));
            list.add(student);
        }
        for (Student a:list) {
            System.out.println(a);
        }
        connection.close();
    }
}
/*
5. Druid:数据库连接池实现技术,由阿里巴巴提供的
https://github.com/alibaba/druid
	1. 步骤:
		1. 导入jar包 druid-1.0.9.jar
		2. 定义配置文件:
			* 是properties形式的
			* 可以叫任意名称,可以放在任意目录下
		3. 加载配置文件。Properties
		4. 获取数据库连接池对象:通过工厂来来获取  DruidDataSourceFactory
		5. 获取连接:getConnection
*/
public class DruidDemo {
    public static void main(String[] args) throws Exception {
        //3.加载配置文件
        Properties pro = new Properties();
        InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
        pro.load(is);
        //4.获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(pro);
        //5.获取连接
        Connection connection = dataSource.getConnection();
        
        PreparedStatement preparedStatement = connection.prepareStatement("select * from student2");
        ResultSet resultSet = preparedStatement.executeQuery();
        List<Student> list = new ArrayList<>();
        while(resultSet.next()){
            Student student = new Student();
            student.setId(resultSet.getInt(1));
            student.setName(resultSet.getString(2));
            student.setAge(resultSet.getInt(3));
            student.setSex(resultSet.getString(4));
            list.add(student);
        }
        for (Student a:list) {
            System.out.println(a);
        }
        connection.close();
    }
}

定义工具类

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
    //1.定义成员变量 DataSource
    private static DataSource ds;
    static{
        try {
            //1.加载配置文件
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //2.获取DataSource
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getCon() throws SQLException {
        return ds.getConnection();
    }

    public static DataSource getDs() throws SQLException {
        return ds;
    }

    public static void close(Statement stmt, Connection conn){
        close(null,stmt,conn);
    }

    public static void close(ResultSet resultSet, Statement stmt, Connection conn){
        if(conn != null){
            try {
                conn.close();//归还连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Spring JDBC

Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发

步骤:

  1. 导入jar包

  2. 创建JdbcTemplate对象。依赖于数据源DataSource

    • JdbcTemplate template = new JdbcTemplate(ds);
  3. 调用JdbcTemplate的方法来完成CRUD的操作

    • update():执行DML语句。增、删、改语句
    • queryForMap():查询结果将结果集封装为map集合,将列名作为key,将值作为value 将这条记录封装为一个map集合
      • 注意:这个方法查询的结果集长度只能是1
    • queryForList():查询结果将结果集封装为list集合
      • 注意:将每一条记录封装为一个Map集合,再将Map集合装载到List集合中
    • query():查询结果,将结果封装为JavaBean对象
      • 一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
      • new BeanPropertyRowMapper<类型>(类型.class)
    • queryForObject:查询结果,将结果封装为对象
      • 一般用于聚合函数的查询
public class SpringJDBCDemo {
    private JdbcTemplate jdbcTemplate;
    @Before
    public void init() throws SQLException {
        jdbcTemplate=new JdbcTemplate(JDBCUtils.getDs());
    }

    @Test
    public void testAdd(){
        jdbcTemplate.update("insert into student2(id,name,age,sex) values(?,?,?,?)",5,"赵六",10,"男");
    }
    @Test
    public void testUpdate(){
        jdbcTemplate.update("update student2 set age = ? where id = ?",16,5);
    }
    @Test
    public void testDelete(){
        jdbcTemplate.update("delete from  student2  where id =?",5);
    }
    @Test
    public void testFindOne(){
        List<Student> list = jdbcTemplate.query("select * from student2 where id =?", new BeanPropertyRowMapper<Student>(Student.class),7);
        for (Student a:list
        ) {
            System.out.println(a);
        }
    }

    @Test
    public void testFindAll(){
        List<Student> list = jdbcTemplate.query("select * from student2 ", new BeanPropertyRowMapper<Student>(Student.class));
        for (Student a:list
        ) {
            System.out.println(a);
        }
    }
    @Test
    public void testFindCount(){
        int count = jdbcTemplate.queryForObject("select count(*) from student2",Integer.class);
        System.out.println(count);
    }
}

补充:追光者数据库连接池(Hikari)

import com.sibd.pojo.Student;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class HikariCPDemo {
    public static void main(String[] args) throws SQLException {

        HikariConfig hikariConfig = new HikariConfig("src/hikari.properties");

        HikariDataSource ds = new HikariDataSource(hikariConfig);
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        conn = ds.getConnection();
        statement = conn.createStatement();
        rs = statement.executeQuery("select * from student2");
        while (rs.next()){
            Student student = new Student();
            student.setId(rs.getInt(1));
            student.setName(rs.getString(2));
            student.setAge(rs.getInt(3));
            student.setSex(rs.getString(4));
            System.out.println(student);
        }
        rs.close();
        statement.close();
        conn.close();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我会回答你的问题,以下是常用数据库连接池 DBCP、c3p0Druid 的配置说明: 1. DBCP (Apache Commons DBCP) DBCP 是 Apache Commons 项目中的一个子项目,它是一个纯 Java 实现的数据库连接池。DBCP 的使用非常简单,只需要引入相关的 jar 包即可。以下是 DBCP 的配置说明: ``` # 最大连接数 maxActive=100 # 最大空闲连接数 maxIdle=30 # 最小空闲连接数 minIdle=10 # 获取连接时的最大等待时间,单位为毫秒 maxWait=10000 # 是否开启自动回收空闲连接的线程 removeAbandoned=true # 回收超时时间,单位为秒 removeAbandonedTimeout=180 # 是否开启缓存 PreparedStatement,提高性能 poolPreparedStatements=true # 缓存 PreparedStatement 的最大数量 maxOpenPreparedStatements=100 ``` 2. c3p0 c3p0 是一个开源的 JDBC 数据库连接池,它实现了数据源和 JNDI 绑定,支持 JDBC3 的 Connection 和 Statement 缓存以及 JDBC4 的自动化管理。以下是 c3p0 的配置说明: ``` # 最大连接数 c3p0.maxPoolSize=100 # 最小连接数 c3p0.minPoolSize=10 # 初始化连接数 c3p0.initialPoolSize=10 # 获取连接时的最大等待时间,单位为毫秒 c3p0.checkoutTimeout=10000 # 是否自动回收超时连接 c3p0.autoCommitOnClose=true # 是否开启自动回收空闲连接的线程 c3p0.idleConnectionTestPeriod=60 # 回收超时时间,单位为秒 c3p0.maxIdleTime=1800 # 是否开启缓存 PreparedStatement,提高性能 c3p0.cachePreparedStatements=true # 缓存 PreparedStatement 的最大数量 c3p0.maxStatements=100 ``` 3. Druid Druid 是阿里巴巴开源的一个高性能、可扩展、功能强大的数据库连接池。它主要提供了以下功能:监控统计、防御 SQL 注入、批量处理、数据源加密、日志记录等。以下是 Druid 的配置说明: ``` # 最大连接数 druid.maxActive=100 # 最大空闲连接数 druid.maxIdle=30 # 最小空闲连接数 druid.minIdle=10 # 获取连接时的最大等待时间,单位为毫秒 druid.maxWait=10000 # 是否开启自动回收空闲连接的线程 druid.removeAbandoned=true # 回收超时时间,单位为秒 druid.removeAbandonedTimeout=180 # 是否开启缓存 PreparedStatement,提高性能 druid.poolPreparedStatements=true # 缓存 PreparedStatement 的最大数量 druid.maxOpenPreparedStatements=100 # 是否开启 SQL 执行监控 druid.stat=true # 是否开启防御 SQL 注入功能 druid.filters=stat,wall,log4j ``` 以上就是常用数据库连接池 DBCP、c3p0Druid 的配置说明。希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值