[spring-boot] 配置 MySQL


spring-boot項目 配置MYSQL驅動

maven pom文件中增加依賴

        <!-- MYSQL驅動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

在application.properties中加入配置(注:我的密碼數據庫密碼是空)

#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=

在數據庫中,新建一張表,放入一丟丟的數據(注意:設計表時,要改表的字符集,排序規則,否則亂碼)

在項目中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:

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。版本不匹配便會報驅動類已過時的錯誤

解決方案:更改MySQL的驅動配置(注:以下代碼標紅部分)

#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=

重新啟動:

報錯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=

重新啟動后,白淺女神已經被查詢出來打印在控制台了。

 

 個人筆記,僅供參考,如有問題,請指正。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM