[spring-boot] 配置 MySQL

spring-boot项目 配置MYSQL驱动java

maven pom文件中增长依赖mysql

        <!-- MYSQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

在application.properties中加入配置(注:个人密码数据库密码是空)spring

#MYSQL连接
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=

在数据库中,新建一张表,放入一丢丢的数据(注意:设计表时,要改表的字符集,排序规则,不然乱码)sql

在项目中DemoApplication启动类中增长如下代码数据库

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
 ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args); JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); List<Map<String, Object>> result = jdbcTemplate.queryForList("SELECT * FROM student"); System.out.println(result);
    }

}

从新启动程序服务器

报错1:app

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. 
The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
正在加载类“com.mysql.jdbc.driver”。这已被弃用。新的驱动程序类是'com.mysql.cj.jdbc.driver'。驱动程序经过SPI自动注册,一般不须要手动加载驱动程序类。

报错缘由:mysql5用的驱动url是com.mysql.jdbc.Drivermysql6之后用的是com.mysql.cj.jdbc.Driver。版本不匹配便会报驱动类已过期的错误maven

解决方案:更改MySQL的驱动配置(注:如下代码标红部分)spring-boot

#MYSQL连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=

从新启动:url

报错2

java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone.
You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a
more specifc time zone value if you want to utilize time zone support.
java.sql.sqlException:服务器时区值“”没法识别或表明多个时区。若是要利用时区支持,必须配置服务器或JDBC驱动程序(经过ServerTimeZone配置属性),以使用更具体的时区值。

 错误缘由:在MYSQL6之后,要须要指定时区serverTimezone。

 解决方案:在数据库链接后增长服务时区,时区有不少,能够根据本身的须要自行配置

#MYSQL连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=

从新启动后,白浅女神已经被查询出来打印在控制台了。

 

 我的笔记,仅供参考,若有问题,请指正。

相关文章
相关标签/搜索