在使用JDBC連接訪問MySQL時一般要使用對應版本的驅動。 比如我使用了8.0.11版本的MySQL,對應驅動的Maven描述為:
1 <dependency> 2 <groupId>mysql</groupId> 3 <artifactId>mysql-connector-java</artifactId> 4 <version>8.0.11</version> 5 </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.
高版本的驅動已經由:
1 "com.mysql.jdbc.Driver"
變更為:
1 private static final String DB_DRIVER = "com.mysql.cj.jdbc.Driver";
報錯2:
1 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. 2 創建連接失敗,查看控制台異常信息
這個是安全連接的問題,在sql連接字符串中,添加關於不使用SSL訪問數據數據庫的說明:useSSL=false。
報錯3:
1 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。
完整的數據庫訪問字符串為:
1 private static final String DB_URL = "jdbc:mysql://localhost:3306/jdbc_example?characterEncoding=utf8&useSSL=false&serverTimezone=UTC";