spring boot使用 jdbc+mysql 连接

JDBC是什么


1.创建文件,勾选JDBC和mysql

 pom.xml中添加了mysql驱动包和jdbc启动器(创建项目勾选就不再需要了,需要自取)

	<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
	</dependency> 


	<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jdbc</artifactId>
	</dependency>

2.application.yml添加数据库的 配置

spring:
  datasource:
    username: root
    password: 123456
#    针对mysql8版本以上的驱动包,需要指定时区
    url: jdbc:mysql://127.0.0.1:3306/jdbc?serverTimezong=GMT%2B8
    #    针对mysql8版本以上的驱动包,需要指定新的驱动类
    #driver-class-name: com.mysql.cj.jdbc.Driver

  mysql 8.x版本驱动包,要使用 com.mysql.cj.jdbc.Driver 作为驱动类 

3.测试类中进行测试

package com.cc.springboot;

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 Springboot08DataJdbcApplicationTests {
    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
        System.out.println("dataSource:"+dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

}

 运行结果:

SpringBoot 默认采用的数据源连接池是:com.zaxxer.hikari.HikariDataSource 

数据源相关配置都在 DataSourceProperties 中;

常见错误

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

说明mysql服务器没有启动,需要启动mysql服务, 你用navicat连接试试看是否可以连接,不可以说明  没有启动 ;

The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one

时区异常:需要配置文件中指定时区: jdbc:mysql://127.0.0.1:3306/jdbc?serverTimezone=GMT%2B8 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值