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();
        
	}

}

 

猜你喜欢

转载自blog.csdn.net/qq_41378597/article/details/82883393
今日推荐