1. 程式人生 > >jdbc連線mysql資料庫報時區錯誤和SSL連線錯誤

jdbc連線mysql資料庫報時區錯誤和SSL連線錯誤

錯誤1:時區錯誤

報錯資訊:

com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: 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.

原因: 在使用mysql的jdbc驅動最新版(6.0+)時,遇到資料庫和系統時區差異引起的問題。 

解決辦法:在url後新增引數 serverTimezone=GMT
示例:Connectionconn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase?
serverTimezone=GMT", "root", "123456");

 

注意:之後還可能會發生另一個錯誤!

 

錯誤2:SSL連線錯誤

報錯資訊:

JAVA在連線資料庫執行時出現了一行這樣的紅字:Fri Sep 28 14:34:03 CST 2018 WARN: 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.

原因: MySQL在高版本需要指明是否進行SSL連線。

解決辦法:在上面url的基礎上新增引數 useSSL=false 
示例:Connectionconn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase?
serverTimezone=GMT&useSSL=false
", "root", "123456");

這樣就解決全部問題啦! ^_^

附上示例程式碼: 

package com.mycode.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * jdbc連線mysql
 *
 */
public class JDBC_Test01 {

	public static void main(String[] args) throws Exception {
		// 1.註冊驅動
		Class.forName("com.mysql.cj.jdbc.Driver");
		// 2.獲取連線Connection
		 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase?serverTimezone=GMT&useSSL=false", "root", "123456");
		// 3.得到執行sql語句的物件Statement
		Statement stmt = conn.createStatement();
		// 4.執行sql語句,並返回結果
		ResultSet rs = stmt.executeQuery("select id,name,password,email,birthday from t_user");
		// 5.處理結果
		while (rs.next()) {
			System.out.println(rs.getObject("id"));
			System.out.println(rs.getObject("name"));
			System.out.println(rs.getObject("password"));
			System.out.println(rs.getObject("email"));
			System.out.println(rs.getObject("birthday"));
			System.out.println("------------");
		}
		// 6.關閉Connection
		rs.close();
		stmt.close();
		conn.close();
        
	}

}