最近在学习spring boot配置链接mysql数据源。
步骤如下:
1.添加pom文件依赖
<!--导入JDBC的场景启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<!--导入数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2.配置文件application.properties或者application.yaml文件添加本地数据源配置:
我这里采用yaml,我这里链接的数据库是potato_market,其中url后面添加的serverTimezone=UTC是需要加的,不然会报错,报错如下截图
#数据源连接信息
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/potato_market?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
通过搜索,找到了解决方案:mysql 连接错误The server time zone value '?????????±?????????±???¤' is_七岁-CSDN博客
3.测试
使用spring boot的测试类进行测试,代码如下:
package com.potato.springboot;
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;
import javax.sql.DataSource;
import java.sql.SQLException;
@SpringBootTest
public class SpringBootJDBCTest {
//数据源
@Autowired
DataSource dataSource;
//用于访问数据库的组件
@Autowired
JdbcTemplate jdbcTemplate;
@Test
void printData() throws SQLException {
System.out.println("默认数据源为:" + dataSource.getClass());
System.out.println("数据库连接实例:" + dataSource.getConnection());
//访问数据库user表,查询user表的数据量
Integer i = jdbcTemplate.queryForObject("SELECT count(*) from `user`", Integer.class);
System.out.println("user 表中共有" + i + "条数据。");
}
}
打印结果为: