Mybatis测试环节报Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
1.问题产生
项目测试环节Java调用Mysql驱动连接数据库时产生的问题:
Opening JDBC Connection
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 619 milliseconds ago. The last packet sent successfully to the server was 613 milliseconds ago.
### The error may exist in com/lanyy/dao/TeacherMapper.xml
### The error may involve com.lanyy.dao.TeacherMapper.getTeacher
### The error occurred while executing a query
### Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 619 milliseconds ago. The last packet sent successfully to the server was 613 milliseconds ago.
2.问题排查
mysql版本问题,检测db.properties文件配置项,本项目使用 5.7 版本驱动使用的是 com.mysql.jdbc.Driver
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
pwd=root
报错原因:useSSL=true时,数据库连接安全认证不通过
解决办法:将useSSL=true改为useSSL=false (即可稳定运行)
3.问题解决
3.1 局部修改
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root
pwd=root
本项目使用此方法解决
3.2节为收录解决方法,供参考
3.2 版本替换
1.选择与mysql版本相对于的驱动
2.在url后加入时区: ?serverTimezone=UTC
3.更改驱动的类名为:com.mysql.cj.jdbc.Driver
更换JDBC驱动:使用:com.mysql.cj.jdbc.Driver (注:需指定时区&serverTimezone=UTC)
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
pwd=root
更换连接驱动的版本 本项目使用5.1.47版本更换为8.0.20版本
<dependencies> <!-- mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!-- mybatis 配置 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!-- junit测试单元 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> </dependency> <!-- Lombok插件引入自动生成实体类中的set get方法 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.18</version> </dependency> </dependencies>
mysql版本更换
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
了解更多知识请戳下: