> 文档中心 > JDBC 获取数据库连接时报异常 MySQLNonTransientConnectionException

JDBC 获取数据库连接时报异常 MySQLNonTransientConnectionException


问题描述

在手写 获取数据库连接 时,发生如下的报错:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client

代码如下:

public class ConnectionTest {    @Test    public void testConnection1() throws SQLException { // 1.提供java.sql.Driver接口实现类的对象 Driver driver = new com.mysql.jdbc.Driver(); // 2.提供 url,指明具体操作的数据 String url = "jdbc:mysql://localhost:3307/test"; // 3.提供 Properties的对象,指明用户名和密码 Properties info = new Properties(); info.setProperty("user", "root"); info.setProperty("password", "123456"); // //4.调用driver的connect(),获取连接 Connection connect = driver.connect(url, info); System.out.println(connect);    }

原因分析:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:客户端不支持服务器请求的认证协议;考虑升级 MySQL 客户端

通过查看报错信息可以初步判断是由于MySQL版本不匹配导致的,经过排查后发现,在原来的代码中使用的是MySQL5版本的驱动,所以在获取Driver实现类的对象时,全类名为:com.mysql.jdbc.Driver
在这里插入图片描述

而在本地安装了MySQL5和MySQL8,端口3307又是设置在MySQL8上使用的,而在MySQL8 版本的驱动中,获取Driver实现类的对象时,全类名为:com.mysql.cj.jdbc.Driver
在这里插入图片描述

所以会出现版本不匹配的问题。


解决方案:

在知道了问题原因的情况下,我们只需要将使用的MySQL数据库版本与驱动版本相对应就可以解决问题了!

修改后的代码如下:

public class ConnectionTest {    @Test    public void testConnection1() throws SQLException { // 1.提供java.sql.Driver接口实现类的对象 Driver driver = new com.mysql.jdbc.Driver();   // 对应 MySQL5 版本的驱动// Driver driver = new com.mysql.cj.jdbc.Driver();   // 对应 MySQL8 版本的驱动 // 2.提供 url,指明具体操作的数据 String url = "jdbc:mysql://localhost:3306/test";   // 对应 MySQL5 版本的数据库// String url = "jdbc:mysql://localhost:3307/test";   // 对应 MySQL8 版本的数据库 // 3.提供 Properties的对象,指明用户名和密码 Properties info = new Properties(); info.setProperty("user", "root"); info.setProperty("password", "123456"); // //4.调用driver的connect(),获取连接 Connection connect = driver.connect(url, info); System.out.println(connect);    }

空气商城