JDBC 数据库连接池


在这里插入图片描述

一、什么是数据库连接池

概念:存放数据库连接的一个容器(集合)Connection
当系统运行起来之后,这个连接池就被创建,在这个连接池当中,会申请一些对象,当有用户来访问数据库的时候,就从这个连接池当中获取连接对象,用户访问结束之后,连接池对象会归还给容器

二、为什么需要数据库连接池?

数据库连接的创建和销毁是一项资源密集型操作,它涉及到网络通信和权限验证等操作,因此开销较大。在高并发的应用中,频繁地创建和销毁连接会导致系统性能下降,甚至引发连接泄漏等问题。数据库连接池的引入可以解决这些问题,具体好处包括:

  • 资源重用:连接池可以重复使用现有的连接,避免了频繁创建和销毁连接的开销。
  • 减少连接等待时间:连接池通常会预先创建一些连接,当应用程序需要连接时,可以立即获取可用连接,降低了连接等待时间。
  • 连接管理:连接池负责连接的管理,包括连接的创建、销毁、超时检测等,减轻了开发人员的工作负担。
  • 性能提升:通过连接池可以控制并发连接数,避免了数据库服务器被大量连接请求压垮。

三、JDBC 数据库连接池的实现

JDBC 数据库连接池通常由以下几个关键组件构成:

  • 连接池管理器:用于管理连接的创建、分配、释放等操作。
  • 连接池:实际存放数据库连接的容器。
  • 连接对象:表示一个数据库连接的对象,包括连接信息、状态等。
  • 连接池配置:包括最大连接数、最小连接数、连接超时时间等参数。

四、C3P0的使用

1、加入c3p0 jar包

在这里插入图片描述

2、配置xml文件

在这里插入图片描述

3、c3p0-config.xml模板

<c3p0-config>
    <!--使用默认的配置读取数据库连接池对象 -->
    <default-config>
        <!--  连接参数 -->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/ScienceDB?serverTimezone=UTC</property>
        <property name="user">root</property>
        <property name="password"></property>

        <!-- 连接池参数 -->
        <!--初始化申请的连接数量-->
        <property name="initialPoolSize">5</property>
        <!--最大的连接数量-->
        <property name="maxPoolSize">20</property>
        <!--超时时间-->
        <property name="checkoutTimeout">3000</property>
    </default-config>
</c3p0-config>

4、C3P0的使用

public void sumSelect(String a) throws SQLException {
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        Connection conn=dataSource.getConnection();
        ResultSet rs=conn.prepareStatement("select s.*,c.c_name,sc.s_score from Student s,Score sc ,Course c\n" +
                "where s.s_id=sc.s_id and sc.c_id=c.c_id and s.s_id='"+a+"'").executeQuery();
        while (rs.next()){
            String s_id=rs.getString(1);
            String s_name=rs.getString(2);
            String s_birth=rs.getString(3);
            String s_sex=rs.getString(4);
            String c_name=rs.getString(5);
            int zf=rs.getInt(6);
            System.out.println(s_id+"\t"+s_name+"\t"+s_birth+"\t"+s_sex +"\t"+c_name+"\t"+zf);

        }
        conn.close();//释放连接----》将当前的工作连接,释放为空闲连接
    }

五、Druid的使用

1、加入Druid jar包

在这里插入图片描述

2、定义配置文件:

是properties形式的
在这里插入图片描述

driverClassName =com.mysql.cj.jdbc.Driver;
url=jdbc:mysql://localhost:3306/20231202DB?useServerPrepStmts=true;
username=root;
password=root;
#初始化连接数
initialSize=10;
#最大等待时间
maxwait=5000
#最大连接数
maxActive=50;
minIdle=5;

3、Druid连接池的使用

 public void druidTest() throws Exception {
        Properties properties=new Properties();
        HashMap map=new HashMap();
        map.put("driverClassName","com.mysql.cj.jdbc.Driver");
        map.put("url","jdbc:mysql://localhost:3306/20231202DB?serverTimezone=UTC");
        map.put("username","root");
        map.put("password","");
        map.put("initialSize","10");
        map.put("maxActive","30");
        map.put("maxWait","1000");
        properties.load(new FileInputStream("src\\jdbc.properties"));
        DataSource dataSource= DruidDataSourceFactory.createDataSource(map);
        Connection conn=dataSource.getConnection();
        ResultSet rs=conn.prepareStatement("select count(*) s from film_information").executeQuery();
        while (rs.next()){
            int tps=rs.getInt("s");
            System.out.println(tps);
        }
        conn.close();//释放连接----》将当前的工作连接,释放为空闲连接
    }

六、HikariCP的使用

1、加入HikariCP jar包

在这里插入图片描述

2、配置文件

在代码中配置 HikariCP 连接池。以下是一个示例配置:

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

public class DatabaseConnectionManager {
    private static HikariConfig config = new HikariConfig();
    private static HikariDataSource dataSource;

    static {
        config.setJdbcUrl("jdbc:mysql://localhost:3306/mydatabase");
        config.setUsername("root");
        config.setPassword("password");
        config.setMaximumPoolSize(10); // 最大连接数
        config.setMinimumIdle(5); // 最小空闲连接数
        config.setConnectionTimeout(30000); // 连接超时时间,单位毫秒
        config.setIdleTimeout(600000); // 空闲连接超时时间,单位毫秒
        config.setMaxLifetime(1800000); // 最大生命周期时间,单位毫秒

        dataSource = new HikariDataSource(config);
    }

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

3、HikariCP的使用

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {
    public static void main(String[] args) {
        try (Connection connection = DatabaseConnectionManager.getConnection()) {
            String sql = "SELECT * FROM users";
            try (PreparedStatement preparedStatement = connection.prepareStatement(sql);
                 ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    int userId = resultSet.getInt("id");
                    String username = resultSet.getString("username");
                    String email = resultSet.getString("email");
                    System.out.println("User ID: " + userId + ", Username: " + username + ", Email: " + email);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

七、DBCP的使用

1、加入DBCP jar包

在这里插入图片描述

2、配置文件

#数据库连接地址 
#url=jdbc:mysql://localhost:3306/数据库名(?配置参数)
url=jdbc:mysql://localhost:3306/express_manage?useUnicode=true&characterEncoding=utf-8
#数据库驱动类的全名
driverClassName=com.mysql.jdbc.Driver
#数据库帐号
username=root
#数据库密码 等于号后面直接填密码,不需要引号,密码为空时可以不填或 ""
password=
#初始化连接池时,创建的连接数量
initialSize=5
#连接池的最大连接容量,连接使用完后不释放会很容易达到最大值,导致之后的连接被卡住
maxActive=20
#空闲时允许保留的最大连接数量
maxIdle=5
#空闲时允许保留的最小连接数量
minIdle=5
#排队等候的超时时间(毫秒)
maxWait=3000

3、DBCP使用

新增

public class DBCPTest {
    //全局变量
    private static DataSource ds = null;
    static {
        Properties ppt = new Properties();
        InputStream is = DBCPTest.class.getClassLoader().getResourceAsStream("dbcp.properties");
        try {
            ppt.load(is);
            ds = BasicDataSourceFactory.createDataSource(ppt);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws Exception {
        //文件的输入流
        InputStream is = DBCPTest.class.getClassLoader().getResourceAsStream("dbcp.properties");
        //将配置文件, 转换为Properties对象
        Properties ppt = new Properties();
        ppt.load(is);
        //通过连接池的工厂类(DruidDataSourceFactory)的创建连接池的方法(createDataSource())
        DataSource ds = BasicDataSourceFactory.createDataSource(ppt);

       //从连接池中 获取连接对象
       Connection conn = ds.getConnection();
        //通过连接对象,创建SQL对象
        Statement state = conn.createStatement();
        //通过SQL对象,执行SQL语句,以
        state.execute("insert into user value ('huang','123')");
        //释放资源
        conn.close();
        state.close();
    }
}

  • 38
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值