数据库乱码解决
说明:在新建数据库的时候记得选择编码格式,一般中文选择utf-8,数据库在建表和每个字段都会选择字符编码,出现字符编码问题首先确保字段编码是否正确;
排查原因:
打断点,查看到底是在执行存数据库操作之前就已经乱码了,还是存数据库操作后乱码的。
前者解决方案:
在web.xml里面加上:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param:>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在配置jdbc数据源的时候加上:
jdbc:mysql://127.0.0.1:3306/logistics?useUnicode=true&characterEncoding=UTF-8
存数据库操作后乱码,解决方案:
登录数据库,执行如下sql:
show variables like 'character%';
结果:
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | latin1 |
| character_set_system | utf8 |
说明在安装数据库的时候,character_set_database,character_set_server编码格式设置错误。
解决:
找到mysql安装路径下的my.cnf文件在[mysqld]下添加如下两行:
character_set_server=utf8
init_connect='SET NAMES utf8'
再次查看,问题解决:
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8