Spring Boot配置数据源(mysql)

最近在学习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 + "条数据。");
    }

}

打印结果为:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值