JAVA JDBC使用mysql8.0.jar包连接数据库的小坑

喜欢用新不用久,所以我装软件基本都是遵循去下载安装最新版本的软件,毕竟新的软件功能多,虽然小坑和小问题也多,但是大部分坑你搜一搜网上都有前人给你填平了,这里记录一下自己学习JAVA JDBC连接数据库时的一个小问题

就是连接数据库驱动的时(使用了mysql-connector-java-8.0.11.jar驱动包),如下

 

 //驱动类com.mysql.jdbc.Driver
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("数据库加载成功!"); 
// 建立与数据库的Connection连接
 Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8","root","admin");    

 

会出现警告①

 

Establishing SSL connection without server's identityverification 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 optionisn't set. For compliance with existing applications not using SSL theverifyServerCertificate property is set to 'false'. You need either toexplicitly disable SSL by setting useSSL=false, or set useSSL=true and providetruststore for server certificate verification.

原因

驱动程序的描述字符串com.mysql.jdbc.Driver是mysql5.0及以前的老写法

而mysql6.0以后 包括我用的8.0需要这样写com.mysql.cj.jdbc.Driver

警告②

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.
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.

原因

MySQL在高版本需要指明是否进行SSL连接。解决方案: 在mysql连接字符串url中加入ssl=true或者false即可,如下所示

"jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong"

完整的代码如下

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class TestJDBC {
	public static void main(String[] args) {
		//初始化驱动
		try {
            //老版驱动类com.mysql.jdbc.Driver
            //如果忘记了第一个步骤的导包,就会抛出ClassNotFoundException
			Class.forName("com.mysql.cj.jdbc.Driver");
			System.out.println("数据库加载成功!");
			
			Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?"
					                                 + "useUnicode=true&characterEncoding=utf8&"
					                                 + "useSSL=false&serverTimezone=Hongkong","root","admin");
			System.out.println("连接成功,获取连接对象: " + c);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}

其中test是本机数据库名,root和admin是mysql安装时创建的账户和密码。

serverTimezone=HongKong 是设置时区,可以填UTC、Asia/Shanghai等等,UTC要比中国时区早8个小时。

待更新。。

你可能感兴趣的:(JAVA)