1. 程式人生 > >高版本MySQL(5.7,5.8)的JDBC連線新問題

高版本MySQL(5.7,5.8)的JDBC連線新問題

在使用JDBC連線訪問MySQL時一般要使用對應版本的驅動。 比如我使用了8.0.11版本的MySQL,對應驅動的Maven描述為:

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

然後遇到了驅動問題、SSL安全訪問的問題和時區問題。
報錯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"

變更為

private static final String DB_DRIVER = "com.mysql.cj.jdbc.Driver"
;

報錯2:

Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property
is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. 建立連線失敗,檢視控制檯異常資訊

這個是安全連線的問題,在sql連線字串中,新增關於不使用SSL訪問資料資料庫的說明:useSSL=false。

報錯3:

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。

完整的資料庫訪問字串為:

private static final String DB_URL = "jdbc:mysql://localhost:3306/jdbc_example?characterEncoding=utf8&useSSL=false&serverTimezone=UTC";