Public Key Retrieval is not allowed
最近使用
JDBC
连接MySQL
频繁出现如下报错:
java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowe
这段代码是一个 Java
异常错误信息,其中包含了以下关键信息:
- 错误类型:java.sql.SQLNonTransientConnectionException
- 错误描述:Public Key Retrieval is not allowed.
- 抛出异常的位置:com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825)
根据异常信息提示,这是 MySQL
数据库连接时出现的问题。
更具体地说,可能是由于连接字符串 URL
中缺少 allowPublicKeyRetrieval=true
参数导致的。
为了解决该异常,可以尝试采取以下几种方法:
- 修改
MySQL
数据库连接字符串URL
,在末尾追加?allowPublicKeyRetrieval=true
参数。如:String url = "jdbc:mysql://localhost:3306/mydatabase?allowPublicKeyRetrieval=true&useSSL=false";
- 如果使用的是
Java 8
及以上版本,可以将SSL
模式设置为false
,即在JDBC
驱动程序中通过添加一个额外属性来关闭SSL
:
此时可以不需要String url = "jdbc:mysql://localhost:3306/mydatabase?sslMode=DISABLED";
allowPublicKeyRetrieval=true
参数选项。
但其根本原因是
MySQL
使用了Innovation
版本,而驱动版本不一致导致的
<!-- 低版本驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- 高版本驱动 此版本为 Innovation 版本驱动-->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
升级
MySQL
驱动Innovation
版本后修改MySQL
数据库连接字符串URL
如下:
- xm文件
jdbc:mysql://localhost:3306/db?allowPublicKeyRetrieval=true&useUnicode=true&createDatabaseIfNotExist=true&characterEncoding=UTF8&useSSL=false&serverTimeZone=Asia/Shanghai&sslMode=DISABLED
- 非xml文件
jdbc:mysql://localhost:3306/db?allowPublicKeyRetrieval=true&useUnicode=true&createDatabaseIfNotExist=true&characterEncoding=UTF8&useSSL=false&serverTimeZone=Asia/Shanghai&sslMode=DISABLED