1. JDBC连接MySQL报错Communications link failure
Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
- 已经创建新用户,并授权相关操作权限,可从任意主机访问MySQL
- 问题的原因在于,MySQL默认监听localhost:3306,因此无法远程连接
- 解决办法:
ubuntu18.04 系统中
- 查看3306端口的监听情况
netstat -an | grep 3306
发现监听127.0.0.1:3306
- 修改MySQL配置
vim /etc/mysql/mysql.conf.d/mysqld.cnf
- 找到:
bind-address=127.0.0.1
- 将其修改为:
bind-address=0.0.0.0
- 记得重启MySQL服务
service mysql restart
2. 数据库中文乱码问题
若已知要存储的数据中需要有中文,最好创建数据库的时候,就把默认字符集设置为utf8
CREATE DATABASE 数据库名 CHARACTER SET utf8;
# 更改数据库默认字符集
alter database 数据库名 default character set utf8;
设置了之后,使用JDBC提交插入语句时,发现执行的结果仍然是中文乱码或者问号,需要在连接数据库的URL中更改,如下:
jdbc:mysql://IP地址:3306/数据库名?useUnicode=true&characterEncoding=utf8