关于spring boot使用 jdbc+mysql 连接的问题
1.创建文件,勾选JDBC和mysql

pom.xml中添加了mysql驱动包和jdbc启动器
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
上一篇:java实现抽奖功能解析
栏 目:JAVA代码
下一篇:解决IDEA 2022 Translation 翻译文档失败: 未知错误的问题
本文标题:关于spring boot使用 jdbc+mysql 连接的问题
本文地址:http://www.codeinn.net/misctech/205051.html


阅读排行
- 1Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 2Java Swing组件BoxLayout布局用法示例
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4java中-jar 与nohup的对比
- 5深入理解Java中的克隆
- 6Java中自定义异常详解及实例代码
- 7解析SpringSecurity+JWT认证流程实现
- 8java读取excel文件的两种方法
- 9深入解析java虚拟机
- 10spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)




