Hibernate连接MySQL数据库乱码相关问题

1、查看MySQL字符编码

  >show variables like 'character%'; #执行编码显示

  其中character_set_client,character_set_results,character_set_connection三个运行变量是造成乱码的关键

2、修改MySQL编码格式为UTF8

  编辑my.ini,(注意:不是utf-8,也要注意大小写)

  找到客户端配置[client] 在下面添加

  ### 默认字符集为utf8

  default-character-set=utf8

  在找到[mysqld] 添加

  ### 默认字符集为utf8

  default-character-set=utf8

  ### (设定连接mysql数据库时使用utf8编码,以让mysql数据库为utf8运行)

  init_connect='SET NAMES utf8'

  修改好后,重新启动mysql 即可,查询一下show variables like 'character%';

3、同时创建hibernate数据库时需要显示设置数据库的编码方式为utf8。示例:

  create database daycode default charset=utf8;

4、做完这两步还是不行,需要修改hibernate的配置文件hibernate.cfg.xml,在配置文件配置hibernate.connection.url属性。示例:

  <property name="hibernate.connection.url">
          <![CDATA[jdbc:mysql://localhost:3306/daycode?useUnicode=true&characterEncoding=utf8]]>
  </property>

注意:此字符串不能写为jdbc:mysql://localhost:3306/daycode?useUnicode=true&characterEncoding=utf8,不然会出现编译错误,错误提示为将&连接符改为;。

设置这些之后乱码问题就解决了。

5、设置完以上内容以后,发现在cmd下面查询时会出现中文乱码,

在mysql>下输入以下命令可以解决这个问题

 set names gbk; 

原文地址:https://www.cnblogs.com/dolphi/p/4060560.html