JDBC連線Mysql資料庫出現的問題彙總
最近安裝了一個mysql 8.0
版本的資料庫,在程式中連線的時候可謂是狀況不斷。之前也會遇到一些問題,這裡就對使用 JDBC 連線mysql 會出現的問題做一個彙總。
在此之前說明一下環境:
-
開發工具:IDEA
-
mysql版本: 8.0.12 for Win64 on x86_64 (SQL/">MySQL Community Server - GPL)
- mysql驅動包:8.0.12
驅動包URL 的改變
異常資訊
Loading classcom.mysql.jdbc.Driver
. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver
. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
原因
通過異常我們可以發現,新的驅動url是com.mysql.cj.jdbc.Driver
,經過在網上查閱資料發現,從mysql6
開始,驅動包開始使用新的驅動url。如果使用最新的 url ,會報驅動已過時的錯誤。
解決方法
將驅動 URL 由com.mysql.jdbc.Driver
換成com.mysql.cj.jdbc.Driver
SSL 警告
警告資訊
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.
原因
對警告資訊翻譯如下。
不建議在沒有伺服器身份驗證的情況下建立SSL連線。根據MySQL 5.5.45+,如果未設定顯式選項,則預設情況下必須建立5.6.26+和5.7.6+要求的SSL連線。對於不使用SSL的現有應用程式,ValuyServer證書屬性設定為“false”。您需要通過設定useSSL=false來顯式禁用SSL,或者設定useSSL=true並提供用於伺服器證書驗證的信任庫`。
解決方法
一般在開發中基本不需要使用 SSL 連線,在連線字串後新增useSSL=false
引數就行。但是如果真的有 SSL 連線的需要,則在驅動 URL 後新增useSSL=true
引數。
jdbc:mysql://localhost:3306/dbname?characterEncoding=UTF-8&useSSL=false
時區問題
異常資訊
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
解決方法
-
連線字串後新增引數
&serverTimezone=GMT%2B8
,最終連線字串如下:jdbc:mysql://localhost:3306/dbname?characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
-
修改資料庫時間。先通過命令列連上資料庫,依次輸入命令及其輸出如下
mysql> show variables like "%time_zone"; +------------------+--------+ | Variable_name| Value| +------------------+--------+ | system_time_zone || | time_zone| SYSTEM | +------------------+--------+ 2 rows in set, 1 warning (0.04 sec) mysql> set global time_zone="+8:00"; Query OK, 0 rows affected (0.01 sec)
XML 配置檔案中 & 的轉義
異常資訊
org.mybatis.generator.exception.XMLParserException: XML Parser Error on line 16: 對實體 “useSSL” 的引用必須以 ‘;’ 分隔符結尾。
原因
這是我在使用mybatis generator
時出現的錯誤。當時我想在連線字串後加上useSSL
引數,但是由於在XML
檔案中,&
是被禁止的,所以需要使用&
的時要用它的轉義&
來代替。
解決方法
將連線字串中的&
符號改成&
詳細連線字串參考
jdbc:mysql://127.0.0.1:3306/dbname?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&serverTimezone=GMT%2B8&verifyServerCertificate=false&autoReconnct=true&autoReconnectForPools=true&allowMultiQueries=true
當然如果是使用 XML 作為配置檔案,需要將 連線字串中的&
符號改成&