1.使用的jar包版本:mysql-connector-5.1.0+
//1.注冊驅動 Class.forName("com.mysql.jdbc.Driver"); //2.獲取連接對象 conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/數據庫名稱", "用戶名", "密碼");
2.使用的jar包版本:mysql-connector-8.0.0+
如果使用第一種情況的Java代碼,會出現以下錯誤:
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. 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.
出錯原因:
1.驅動程序的描述字符串com.mysql.jdbc.Driver是mysql5.0及以前的老寫法,而mysql6.0+(包括我用的8.0+)需要這樣寫com.mysql.cj.jdbc.Driver。
2.MySQL在高版本需要指明是否進行SSL連接和服務器時區(時區必須指明)。解決方案: 在mysql連接字符串url中加入ssl=false(或者true,默認為true)&&serverTimezone=時區。
需要將Java代碼更改為:
//1.注冊驅動 Class.forName("com.mysql.cj.jdbc.Driver"); //2.獲取連接對象 conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/數據庫名稱?useSSL=false&serverTimezone=服務器時區", "用戶名", "密碼"); /* 與5.0+版本的對比:驅動路徑變了;多出了useSSL=false&serverTimezone=時區。 useSSL=false:8.0之前是需要連接數據庫是需要建立ssl連接,而8.0之后不需要了,所以需要將其關閉。 serverTimezone可以填UTC、Asia/Shanghai等等,UTC要比中國時區早8個小時。我寫的是serverTimezone=Hongkong
*/
注意:Java代碼怎么寫與jar包的版本有關。
建議:mysql5.0+版本使用mysql-connector-5.0+ jar包,mysql8.0+版本使用mysql-connector-8.0+ jar包。