JDBC连接MySQL抛Can`t get host name for your address异常的处理

很多教程,教材和视频讲JDBC。上来第一章就会讲“与MySQL”连接,而且一般都没有任何错误,写了三行代码,完美连接。

public static void main(String[] args) throws SQLException, ClassNotFoundException {
		Class.forName( "com.mysql.jdbc.Driver" );
		String url = "jdbc:mysql://127.0.0.1:3306/aaa";
		Connection con = DriverManager.getConnection(url,"root","root");
		System.out.println(con);
	}
神奇地是,自己照着写了代码连接,很可能出现以下错误:

本机root用户名和密码都是root,代码写得没问题。但就是无法连接MySQL。

更奇特的是,在这个情况下,Sqlyong还可以正常连接登录。用JDBC连接OracleSQL,连接也没问题。可以确定

1.不是代码的问题

2.不是JDBC配置的问题。

这就很令人头大了。

****************************************************************************************************************************************************************************************

这个问题的原因,查了多方面的资料,确定是Winsock底层出现的错误。可以开启命令提示符,输入:

netsh winsock reset
来重置底层的winsock。

输入过程中防火墙会检测到并报出异常行为:



可以看到执行本条命令后,实质上是命令提示符运行了netsh工具,将注册表中的设置进行重置。直接点击允许此程序所有操作。

重启之后连接MySQL。可以看到连接成功,MySQL给出WARNING:

hu May 18 23:27:26 GMT+08:00 2017 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字符串中加入: ?characterEncoding=utf8&useSSL=true 即可。

猜你喜欢

转载自blog.csdn.net/xiblade/article/details/72516223