1、导入JDBC场景
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency>
2、导入要操作的数据库
我选择的是mysql5,到https://mvnrepository.com/可以找到对应的依赖
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.25</version> </dependency>
底层配置好的连接池是HikariDataSource
3、修改配置项(我使用的是yaml配置)
spring: datasource: url: jdbc:mysql://localhost:3306/mybatisdb username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver jdbc: template: query-timeout: 3
4、在测试类里测试一下
package demo.boot.demo03; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.jdbc.core.JdbcTemplate; @Slf4j @SpringBootTest class Demo03ApplicationTests { @Autowired JdbcTemplate jdbcTemplate; @Test void contextLoads() { String sql = "select count(*) from user"; Long aLong = jdbcTemplate.queryForObject(sql, long.class); log.info("总数为:"+aLong); } }
成功连接,并执行了查询操作。