首页 > 解决方案 > SpringBoot中如何连接MySql数据库?

问题描述

我是 Spring Boot 的初学者,我想连接到 MySQL 数据库(8.0.15),但是当我运行我的应用程序时,我遇到了以下异常,我无法理解它。我该如何解决这个问题?

java.sql.SQLException:连接属性“zeroDateTimeBehavior”仅接受以下形式的值:“exception”、“round”或“convertToNull”。值“CONVERT_TO_NULL”不在此集中。

应用程序属性

spring.datasource.url= jdbc:mysql://localhost:3306/sakila?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=root

标签: javamysqlspring

解决方案


第 1 步 - 将数据库连接器的依赖项添加到 pom.xml MySQL 的示例如下所示。

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

如果您想连接到 oracle 数据库,您可以使用类似于下图所示的依赖项。

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.1</version>
</dependency>

第 2 步 - 从 pom.xml 中删除 H2 依赖项或至少将其范围设为测试

<!--
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>
-->

第 3 步 - 设置您的 My SQL 数据库 我们需要使用模式和表来设置您的数据库。

For an example, check out - https://github.com/in28minutes/jpa-with-hibernate#installing-and-setting-up-mysql

第 4 步 - 配置与您的数据库的连接 配置 application.properties 以连接到您的数据库。

My SQL 的示例如下所示:

spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/todo_example
spring.datasource.username=todouser
spring.datasource.password=YOUR_PASSWORD

spring.jpa.hibernate.ddl-auto

Spring Boot 根据您是否连接到嵌入式数据库为此选择默认值。

Embedded Databases - default create-drop
Other Databases - default none

这是所有选项的快速指南

none : No action will be performed.
create-only : Database creation will be generated from entities.
drop : Database dropping will be generated from entities.
create : Database dropping will be generated followed by database creation.
validate : Validate entites with the database schema
update: Update the database schema based on the entities

第 5 步 - 重新启动,您就准备好了!而已


推荐阅读