1.JDBC的概念

1.1JDBC的概念

  • JDBC:Java Database Connectivity,意为Java数据库连接。
  • JDBC是Java提供的一组独立于任何数据库管理系统的API。
  • Java提供接口规范,由各个数据库厂商提供接口的实现,厂商提供的实现类封装成jar文件,也就是我们俗称的数据库驱动jar包。
  • 学习JDBC,充分体现了面向接口编程的好处,程序员只关心标准和规范,而无需关注实现过程。

img

1.2JDBC的核心组成

  • 接口规范:
    • 为了项目代码的可移植性,可维护性,SUN公司从最初就制定了Java程序连接各种数据库的统一接口规范。这样的话,不管是连接哪一种DBMS软件,Java代码可以保持一致性。
    • 接口存储在java.sql和javax.sql包下。
  • 实现规范:
    • 因为各个数据库厂商的DBMS软件各有不同,那么各自的内部如何通过SQL实现增、删、改、查等操作管理数据,只有这个数据库厂商自己更清楚,因此把接口规范的实现交给各个数据库厂商自己实现。
    • 厂商将实现内容和过程封装成jar文件,我们程序员只需要将jar文件引入到项目中集成即可,就可以开发调用实现过程操作数据库了。

2.JDBC快速入门

2.1准备工作

1). 创建一个maven项目

img

2). 创建一个数据库 web,并在该数据库中创建user表

1
2
3
4
5
6
7
8
9
create table user(
id int unsigned primary key auto_increment comment 'ID,主键',
username varchar(20) comment '用户名',
password varchar(32) comment '密码',
name varchar(10) comment '姓名',
age tinyint unsigned comment '年龄'
) comment '用户表';

insert into user(id, username, password, name, age) values (1, 'daqiao', '123456', '大乔', 22),(2, 'xiaoqiao', '123456', '小乔', 18),(3, 'diaochan', '123456', '貂蝉', 24),(4, 'lvbu', '123456', '吕布', 28),(5, 'zhaoyun', '12345678', '赵云', 27);

2.2代码实现

具体的代码为:

1). 在 pom.xml 文件中引入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependencies>
<!-- MySQL JDBC driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.3</version>
<scope>test</scope>
</dependency>
</dependencies>

2). 在 src/main/test/java 目录下编写测试类,定义测试方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class JDBCTest {

/** * 编写JDBC程序, 查询数据 */@Test
public void testJdbc() throws Exception {
// 获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web", "root", "1234");
// 创建预编译的PreparedStatement对象
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM user WHERE username = ? AND password = ?");
// 设置参数
pstmt.setString(1, "daqiao"); // 第一个问号对应的参数
pstmt.setString(2, "123456"); // 第二个问号对应的参数
// 执行查询
ResultSet rs = pstmt.executeQuery();
// 处理结果集
while (rs.next()) {
int id = rs.getInt("id");
String uName = rs.getString("username");
String pwd = rs.getString("password");
String name = rs.getString("name");
int age = rs.getInt("age");

System.out.println("ID: " + id + ", Username: " + uName + ", Password: " + pwd + ", Name: " + name + ", Age: " + age);
}
// 关闭资源
rs.close();
pstmt.close();
conn.close();
}

}

2.3步骤总结

  • 1.注册驱动【依赖的驱动类,进行安装】/注册pom
  • 2.获取连接【Connection建立连接】
  • 3.创建发送SQL语句对象【Connection创建发送SQL语句的Statement】
  • 4.发送SQL语句,并获取返回结果【Statement 发送sql语句到数据库并且取得返回结果】
  • 5.结果集解析【结果集解析,将查询结果解析出来】
  • 6.资源关闭【释放ResultSet、Statement 、Connection】

3.核心API理解

3.1 注册驱动(我们这里用导入pom.xml依赖替代了这一步)

  • Class.forName(“com.mysql.cj.jdbc.Driver”);
  • 在 Java 中,当使用 JDBC(Java Database Connectivity)连接数据库时,需要加载数据库特定的驱动程序,以便与数据库进行通信。加载驱动程序的目的是为了注册驱动程序,使得 JDBC API 能够识别并与特定的数据库进行交互。
  • 从JDK6开始,不再需要显式地调用 Class.forName() 来加载 JDBC 驱动程序,只要在类路径中集成了对应的jar文件,会自动在初始化时注册驱动程序。

3.2 Connection

  • Connection接口是JDBC API的重要接口,用于建立与数据库的通信通道。换而言之,Connection对象不为空,则代表一次数据库连接。
  • 在建立连接时,需要指定数据库URL、用户名、密码参数。
    • URL:jdbc:mysql://localhost:3306/atguigu
      • jdbc:mysql://IP地址:端口号/数据库名称?参数键值对1&参数键值对2
  • Connection 接口还负责管理事务,Connection 接口提供了 commitrollback 方法,用于提交事务和回滚事务。
  • 可以创建 Statement 对象,用于执行 SQL 语句并与数据库进行交互。
  • 在使用JDBC技术时,必须要先获取Connection对象,在使用完毕后,要释放资源,避免资源占用浪费及泄漏。

3.3 Statement

  • Statement 接口用于执行 SQL 语句并与数据库进行交互。它是 JDBC API 中的一个重要接口。通过 Statement 对象,可以向数据库发送 SQL 语句并获取执行结果。

  • 结果可以是一个或多个结果。

    • 增删改:受影响行数单个结果。
    • 查询:单行单列、多行多列、单行多列等结果。
  • 但是

    1
    Statement

    接口在执行SQL语句时,会产生

    1
    SQL注入攻击问题

    :

    • 当使用 Statement 执行动态构建的 SQL 查询时,往往需要将查询条件与 SQL 语句拼接在一起,直接将参数和SQL语句一并生成,让SQL的查询条件始终为true得到结果。

3.4 PreparedStatement

  • PreparedStatement
    
    1
    2
    3



    Statement
    1
    2
    3

    接口的子接口,用于执行

    预编译
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19

    的 SQL 查询,作用如下:

    - 预编译SQL语句:在创建PreparedStatement时,就会预编译SQL语句,也就是SQL语句已经固定。
    - 防止SQL注入:`PreparedStatement` 支持参数化查询,将数据作为参数传递到SQL语句中,采用?占位符的方式,将传入的参数用一对单引号包裹起来'',无论传递什么都作为值。有效防止传入关键字或值导致SQL注入问题。
    - 性能提升:PreparedStatement是预编译SQL语句,同一SQL语句多次执行的情况下,可以复用,不必每次重新编译和解析。

    - 后续的学习我们都是基于PreparedStatement进行实现,更安全、效率更高!

    ### 3.5 ResultSet

    - `ResultSet`是 JDBC API 中的一个接口,用于表示从数据库中`执行查询语句所返回的结果集`。它提供了一种用于遍历和访问查询结果的方式。
    - 遍历结果:ResultSet可以使用 `next()` 方法将游标移动到结果集的下一行,逐行遍历数据库查询的结果,返回值为boolean类型,true代表有下一行结果,false则代表没有。
    - 获取单列结果:可以通过getXxx的方法获取单列的数据,该方法为重载方法,支持索引和列名进行获取。

    ## 4.基于PreparedStatement实现CRUD

    ### 4.1 查询单行单列

    @Test public void querySingleRowAndColumn() throws SQLException { //1.注册驱动

// Class.forName(“com.mysql.cj.jdbc.Driver”);

    //2.获取数据库连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu", "root","atguigu");

    //3.创建PreparedStatement对象,并预编译SQL语句
    PreparedStatement preparedStatement = connection.prepareStatement("select count(*) as count from t_emp");

    //4.执行SQL语句,获取结果
    ResultSet resultSet = preparedStatement.executeQuery();

    //5.处理结果
    while (resultSet.next()){
        int count = resultSet.getInt("count");
        System.out.println("count = " + count);
    }

    //6.释放资源(先开后关原则)
    resultSet.close();
    preparedStatement.close();
    connection.close();

}
1
2
3

### 4.2 查询单行多列

@Test
public void querySingleRow() throws SQLException {
    //1.注册驱动

// Class.forName(“com.mysql.cj.jdbc.Driver”);

    //2.获取数据库连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu","root","atguigu");

    //3.创建PreparedStatement对象,并预编译SQL语句,使用?占位符
    PreparedStatement preparedStatement = connection.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_emp where emp_id = ?");

    //4.为占位符赋值,索引从1开始,执行SQL语句,获取结果
    preparedStatement.setInt(1,1);
    ResultSet resultSet = preparedStatement.executeQuery();

    //5.处理结果
    while (resultSet.next()){
        int empId = resultSet.getInt("emp_id");
        String empName = resultSet.getString("emp_name");
        String empSalary = resultSet.getString("emp_salary");
        int empAge = resultSet.getInt("emp_age");
        System.out.println(empId+"\t"+empName+"\t"+empSalary+"\t"+empAge);
    }

    //6.释放资源(先开后关原则)
    resultSet.close();
    preparedStatement.close();
    connection.close();

}
1
2
3

### 4.3 查询多行多列

@Test
public void queryMoreRow() throws SQLException {
    //1.注册驱动

// Class.forName(“com.mysql.cj.jdbc.Driver”);

    //2.获取数据库连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu","root","atguigu");

    //3.创建Statement对象
    PreparedStatement preparedStatement = connection.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_emp");

    //4.编写SQL语句并执行,获取结果
    ResultSet resultSet = preparedStatement.executeQuery();


    //5.处理结果
    while (resultSet.next()){
        int empId = resultSet.getInt("emp_id");
        String empName = resultSet.getString("emp_name");
        String empSalary = resultSet.getString("emp_salary");
        int empAge = resultSet.getInt("emp_age");
        System.out.println(empId+"\t"+empName+"\t"+empSalary+"\t"+empAge);
    }

    //6.释放资源(先开后关原则)
    resultSet.close();
    preparedStatement.close();
    connection.close();

}
1
2
3

### 4.4 新增

@Test
public void insert() throws SQLException {
    //1.注册驱动

// Class.forName(“com.mysql.cj.jdbc.Driver”);

    //2.获取数据库连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu","root", "atguigu");

    //3.创建Statement对象
    PreparedStatement preparedStatement = connection.prepareStatement("insert into t_emp (emp_name,emp_salary,emp_age)values  (?, ?,?)");

    //4.为占位符赋值,索引从1开始,编写SQL语句并执行,获取结果
    preparedStatement.setString(1,"rose");
    preparedStatement.setDouble(2,666.66);
    preparedStatement.setDouble(3,28);
    int result = preparedStatement.executeUpdate();

    //5.处理结果
    if(result>0){
        System.out.println("添加成功");
    }else{
        System.out.println("添加失败");
    }

    //6.释放资源(先开后关原则)
    preparedStatement.close();
    connection.close();

}
1
2
3

### 4.5 修改

@Test
public void update() throws SQLException {
    //1.注册驱动

// Class.forName(“com.mysql.cj.jdbc.Driver”);

    //2.获取数据库连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu", "root", "atguigu");

    //3.创建Statement对象
    PreparedStatement preparedStatement = connection.prepareStatement("update t_emp set emp_salary = ? where emp_id = ?");

    //4.为占位符赋值,索引从1开始,编写SQL语句并执行,获取结果
    preparedStatement.setDouble(1,888.88);
    preparedStatement.setDouble(2,8);
    int result = preparedStatement.executeUpdate();

    //5.处理结果
    if(result>0){
        System.out.println("修改成功");
    }else{
        System.out.println("修改失败");
    }

    //6.释放资源(先开后关原则)
    preparedStatement.close();
    connection.close();

}
1
2
3

### 4.6 删除

@Test
public void delete() throws SQLException {
    //1.注册驱动

// Class.forName(“com.mysql.cj.jdbc.Driver”);

    //2.获取数据库连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu", "root", "atguigu");

    //3.创建Statement对象
    PreparedStatement preparedStatement = connection.prepareStatement("delete from t_emp where emp_id = ?");

    //4.为占位符赋值,索引从1开始,编写SQL语句并执行,获取结果
    preparedStatement.setInt(1,8);
    int result = preparedStatement.executeUpdate();

    //5.处理结果
    if(result>0){
        System.out.println("删除成功");
    }else{
        System.out.println("删除失败");
    }

    //6.释放资源(先开后关原则)
    preparedStatement.close();
    connection.close();

}
1
2
3
4
5
6
7
8
9

## 5.JDBC扩展

### 5.1实体类和ORM

> - 在使用JDBC操作数据库时,我们会发现数据都是零散的,明明在数据库中是一行完整的数据,到了Java中变成了一个一个的变量,不利于维护和管理。而我们Java是面向对象的,一个表对应的是一个类,一行数据就对应的是Java中的一个对象,一个列对应的是对象的属性,所以我们要把数据存储在一个载体里,这个载体就是实体类!
> - ORM(Object Relational Mapping)思想,**对象到关系数据库的映射**,作用是在编程中,把面向对象的概念跟数据库中表的概念对应起来,以面向对象的角度操作数据库中的数据,即一张表对应一个类,一行数据对应一个对象,一个列对应一个属性!
> - 当下JDBC中这种过程我们称其为手动ORM。后续我们也会学习**ORM框架**,比如MyBatis、JPA等。

package com.atguigu.pojo;
//类名和数据库名对应,但是表名一般缩写,类名要全写!
public class Employee {
private Integer empId;//emp_id = empId 数据库中列名用下划线分隔,属性名用驼峰!
private String empName;//emp_name = empName
private Double empSalary;//emp_salary = empSalary
private Integer empAge;//emp_age = empAge

//省略get、set、无参、有参、toString方法。

}

1
2
3

封装代码:

@Test
public void querySingleRow() throws SQLException {
    //1.注册驱动

// Class.forName(“com.mysql.cj.jdbc.Driver”);

    //2.获取数据库连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu", "root","atguigu");

    //3.创建PreparedStatement对象,并预编译SQL语句,使用?占位符
    PreparedStatement preparedStatement = connection.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_emp where emp_id = ?");

    //4.为占位符赋值,索引从1开始,执行SQL语句,获取结果
    preparedStatement.setInt(1, 1);
    ResultSet resultSet = preparedStatement.executeQuery();
      //预先创建实体类变量
    Employee employee = null;
    //5.处理结果
    while (resultSet.next()) {
        int empId = resultSet.getInt("emp_id");
        String empName = resultSet.getString("emp_name");
        Double empSalary = Double.valueOf(resultSet.getString("emp_salary"));
        int empAge = resultSet.getInt("emp_age");
        //当结果集中有数据,再进行对象的创建
        employee = new Employee(empId,empName,empSalary,empAge);
    }

    System.out.println("employee = " + employee);

    //6.释放资源(先开后关原则)
    resultSet.close();
    preparedStatement.close();
    connection.close();

}
1
2
3
4
5
6
7

### 5.2 主键回显

在数据中,执行新增操作时,主键列为自动增长,可以在表中直观的看到,**但是在Java程序中,我们执行完新增后,只能得到受影响行数,无法得知当前新增数据的主键值**。**在Java程序中获取数据库中插入新数据后的主键值,并赋值给Java对象,此操作为主键回显**。

代码实现:

@Test
public void testReturnPK() throws SQLException {
//1.注册驱动
// Class.forName(“com.mysql.cj.jdbc.Driver”);

   //2.获取数据库连接
   Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu", "root", "atguigu");

   //3.创建preparedStatement对象,传入需要主键回显参数Statement.RETURN_GENERATED_KEYS
   PreparedStatement preparedStatement = connection.prepareStatement("insert into t_emp (emp_name, emp_salary, emp_age)values (?, ?,?)",Statement.RETURN_GENERATED_KEYS);

   //4.编写SQL语句并执行,获取结果
   Employee employee = new Employee(null,"rose",666.66,28);
   preparedStatement.setString(1,employee.getEmpName());
   preparedStatement.setDouble(2,employee.getEmpSalary());
   preparedStatement.setDouble(3,employee.getEmpAge());
   int result = preparedStatement.executeUpdate();

   //5.处理结果
   if(result>0){
       System.out.println("添加成功");
  }else{
       System.out.println("添加失败");
  }

   //6.获取生成的主键列值,返回的是resultSet,在结果集中获取主键列值
   ResultSet resultSet = preparedStatement.getGeneratedKeys();
   if (resultSet.next()){
       int empId = resultSet.getInt(1);
       employee.setEmpId(empId);
  }

  System.out.println(employee.toString());
 
   //7.释放资源(先开后关原则)
   resultSet.close();
   preparedStatement.close();
   connection.close();

}

1
2
3
4
5
6
7
8
9

### 5.3 批量操作

插入多条数据时,一条一条发送给数据库执行,效率低下!

通过批量操作,可以提升多次操作效率!

代码实现:

@Test
public void testBatch() throws Exception {
//1.注册驱动
// Class.forName(“com.mysql.cj.jdbc.Driver”);

//2.获取连接
Connection connection = DriverManager.getConnection(“jdbc:mysql:///atguigu?rewriteBatchedStatements=true”, “root”, “atguigu”);

//3.编写SQL语句
/*
注意:1、必须在连接数据库的URL后面追加?rewriteBatchedStatements=true,允许批量操作
2、新增SQL必须用values。且语句最后不要追加;结束
3、调用addBatch()方法,将SQL语句进行批量添加操作
4、统一执行批量操作,调用executeBatch()
*/
String sql = “insert into t_emp (emp_name,emp_salary,emp_age) values (?,?,?)”;

//4.创建预编译的PreparedStatement,传入SQL语句
PreparedStatement preparedStatement = connection.prepareStatement(sql);

//获取当前行代码执行的时间。毫秒值
long start = System.currentTimeMillis();
for(int i = 0;i<10000;i++){
//5.为占位符赋值
preparedStatement.setString(1, “marry”+i);
preparedStatement.setDouble(2, 100.0+i);
preparedStatement.setInt(3, 20+i);

preparedStatement.addBatch();
}

//执行批量操作
preparedStatement.executeBatch();

long end = System.currentTimeMillis();

System.out.println(“消耗时间:”+(end - start));

preparedStatement.close();
connection.close();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

## 6.连接池

### 6.1 现有问题

> - 每次操作数据库都要获取新连接,使用完毕后就close释放,频繁的创建和销毁造成资源浪费。
> - 连接的数量无法把控,对服务器来说压力巨大。

### 6.2 连接池

> 连接池就是数据库连接对象的缓冲区,通过配置,由连接池负责创建连接、管理连接、释放连接等操作。
>
> 预先创建数据库连接放入连接池,用户在请求时,通过池直接获取连接,使用完毕后,将连接放回池中,避免了频繁的创建和销毁,同时解决了创建的效率。
>
> 当池中无连接可用,且未达到上限时,连接池会新建连接。
>
> 池中连接达到上限,用户请求会等待,可以设置超时时间。

### 6.3 常见连接池

JDBC 的数据库连接池使用 javax.sql.DataSource接口进行规范,所有的第三方连接池都实现此接口,自行添加具体实现!也就是说,所有连接池获取连接的和回收连接方法都一样,不同的只有性能和扩展功能!

- DBCP 是Apache提供的数据库连接池,速度相对C3P0较快,但自身存在一些BUG。
- C3P0 是一个开源组织提供的一个数据库连接池,速度相对较慢,稳定性还可以。
- Proxool 是sourceforge下的一个开源项目数据库连接池,有监控连接池状态的功能, 稳定性较c3p0差一点
- **Druid 是阿里提供的数据库连接池,是集DBCP 、C3P0 、Proxool 优点于一身的数据库连接池,性能、扩展性、易用性都更好,功能丰富**
- **Hikari(ひかり[shi ga li]) 取自日语,是光的意思,是SpringBoot2.x之后内置的一款连接池,基于 BoneCP (已经放弃维护,推荐该连接池)做了不少的改进和优化,口号是快速、简单、可靠。**

![img](https://www.legendkiller.xyz/wp-content/uploads/2025/07/image-68.png)

![img](https://www.legendkiller.xyz/wp-content/uploads/2025/07/image-69.png)

![img](https://www.legendkiller.xyz/wp-content/uploads/2025/07/image-70.png)

### 6.4 Druid连接池使用

使用步骤:

- 引入jar包。
- 编码。

代码实现:

**硬编码方式**(了解):

@Test
public void testHardCodeDruid() throws SQLException {
/*
硬编码:将连接池的配置信息和Java代码耦合在一起。
1、创建DruidDataSource连接池对象。
2、设置连接池的配置信息【必须 | 非必须】
3、通过连接池获取连接对象
4、回收连接【不是释放连接,而是将连接归还给连接池,给其他线程进行复用】
*/

   //1.创建DruidDataSource连接池对象。
   DruidDataSource druidDataSource = new DruidDataSource();

   //2.设置连接池的配置信息【必须 | 非必须】
   //2.1 必须设置的配置
   druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
   druidDataSource.setUrl("jdbc:mysql:///atguigu");
   druidDataSource.setUsername("root");
   druidDataSource.setPassword("atguigu");

   //2.2 非必须设置的配置
   druidDataSource.setInitialSize(10);
   druidDataSource.setMaxActive(20);
   
   //3.通过连接池获取连接对象
   Connection connection = druidDataSource.getConnection();
   System.out.println(connection);

   //基于connection进行CRUD

   //4.回收连接
   connection.close();

}

1
2
3
4
5

**软编码方式(推荐)**:

在项目目录下创建resources文件夹,标识该文件夹为资源目录,创建db.properties配置文件,将连接信息定义在该文件中。

druid连接池需要的配置参数,key固定命名

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///atguigu
username=root
password=atguigu
initialSize=10
maxActive=20

1
2
3

Java代码:

@Test
public void testResourcesDruid() throws Exception {
//1.创建Properties集合,用于存储外部配置文件的key和value值。
Properties properties = new Properties();

   //2.读取外部配置文件,获取输入流,加载到Properties集合里。
   InputStream inputStream = DruidTest.class.getClassLoader().getResourceAsStream("db.properties");
   properties.load(inputStream);

   //3.基于Properties集合构建DruidDataSource连接池
   DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);

   //4.通过连接池获取连接对象
   Connection connection = dataSource.getConnection();
   System.out.println(connection);

   //5.开发CRUD

   //6.回收连接
   connection.close();

}

1
2
3
4
5
6
7
8

### 6.5 HikariCP连接池使用

使用步骤:

- 引入jar包
- 硬编码方式:

@Test
public void testHardCodeHikari() throws SQLException {
/*
硬编码:将连接池的配置信息和Java代码耦合在一起。
1、创建HikariDataSource连接池对象
2、设置连接池的配置信息【必须 | 非必须】
3、通过连接池获取连接对象
4、回收连接
*/
//1.创建HikariDataSource连接池对象
HikariDataSource hikariDataSource = new HikariDataSource();

//2.设置连接池的配置信息【必须 | 非必须】
//2.1必须设置的配置
hikariDataSource.setDriverClassName(“com.mysql.cj.jdbc.Driver”);
hikariDataSource.setJdbcUrl(“jdbc:mysql:///atguigu”);
hikariDataSource.setUsername(“root”);
hikariDataSource.setPassword(“atguigu”);

//2.2 非必须设置的配置
hikariDataSource.setMinimumIdle(10);
hikariDataSource.setMaximumPoolSize(20);

//3.通过连接池获取连接对象
Connection connection = hikariDataSource.getConnection();

System.out.println(connection);

//回收连接
connection.close();
}

1
2
3
4
5

软编码方式:

在项目下创建resources/hikari.properties配置文件

driverClassName=com.mysql.cj.jdbc.Driver
jdbcUrl=jdbc:mysql:///atguigu
username=root
password=atguigu
minimumIdle=10
maximumPoolSize=20

1
2
3

编写代码:

@Test
public void testResourcesHikari()throws Exception{
//1.创建Properties集合,用于存储外部配置文件的key和value值。
Properties properties = new Properties();

   //2.读取外部配置文件,获取输入流,加载到Properties集合里。
   InputStream inputStream = HikariTest.class.getClassLoader().getResourceAsStream("db.properties");
   properties.load(inputStream);
   
   // 3.创建Hikari连接池配置对象,将Properties集合传进去
   HikariConfig hikariConfig = new HikariConfig(properties);
   
   // 4. 基于Hikari配置对象,构建连接池
   HikariDataSource hikariDataSource = new HikariDataSource(hikariConfig);

   // 5. 获取连接
   Connection connection = hikariDataSource.getConnection();
   System.out.println("connection = " + connection);
   
   //6.回收连接
   connection.close();

}
}