SpringBoot-JDBC

1.引入JDBC依赖

<!-- JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- MYSQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
            <scope>runtime</scope>
        </dependency>

2.配置数据库属性

在resource文件夹下新建application.yaml文件,

spring:
  datasource:
    username: root
    password: '1231512315'
    # serverTimezone=UTC 解决时区问题
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    # mysql8 以上使用 cj
    driver-class-name: com.mysql.cj.jdbc.Driver

3.测试连接

package com.example.myblogserver;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class MyblogServerApplicationTests {

    // 自动装配数据源
    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads(){
        // 查看默认的数据源 :class com.zaxxer.hikari.HikariDataSource
        System.out.println(dataSource.getClass());
    }
}
posted @ 2023-01-23 21:13  对CSDN使用炎拳吧  阅读(26)  评论(0编辑  收藏  举报