1. 程式人生 > 實用技巧 >在與mysql的配置當中一定要注意的一點是設定serverTimezone=UTC

在與mysql的配置當中一定要注意的一點是設定serverTimezone=UTC

1、org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'helloController': Unsatisfied dependency expressed through field 'connection'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getConnection' defined in class path resource [cn/chinaunicom/Config/BeanConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.sql.Connection]: Factory method 'getConnection' threw exception; nested exception is 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.

2、Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getConnection' defined in class path resource [cn/chinaunicom/Config/BeanConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.sql.Connection]: Factory method 'getConnection' threw exception; nested exception is 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.

這些報錯都是來自同一個錯誤就是設定serverTimezone=UTC。把這個設定好了就好了。

但是我有一點不清楚:

我明明在.yml檔案裡寫了這個配置,但是就讀不出來,就必須在當時用的時候協商寫好:

    @Bean
    public Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/text?serverTimezone=UTC", "root", "chen792979650");
        
return connection; } }

我配置檔案裡面的東西

server:
  port: 9090
  #配置內嵌伺服器的埠
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    #資料庫url
    url: jdbc:mysql://localhost:3306/text?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
    # 資料庫訪問賬戶
    username: root

明明我配置了的,並且訪問的時候也是用的9090埠,說明這個配置檔案是生效的。但是為什麼不行?

我猜測的原因:應該因為先後順序的原因,在我debug的時候直接先對上面的連線資料庫i的語句執行,再執行配置檔案,但是再我先再連線資料庫操作的時候已經出了問題,直接就報錯了。