在数据库处理的时候,有时会会遇到头疼的乱码问题,中文变成了乱码,或者?,今天就说说解决办法,是我结合网上,以及自己的多次经验写的日志
Windows:找到mysql安装的bin目录下的配置文件my.ini,找到字段 default-character-set,将其改为自己想用的字符集:utf8,要注意的是这里有两个default-character-set,都要改成utf8,是utf8,不是utf-8,若把utf8改成utf-8,则mysql服务打不开,修改完毕,重启Mysql
Linux\Unix:路径/mnt/etc/my.cnf 也是修改 字段 default-character-set 将其设置成集合中文的字符集,若在目录下找不到my.cnf文件和 mysql 文件夹,可以自己新建一个my.cnf文件,但是你的mysql安装目录必须要一致,也可以直接对你要处理的数据库进行编码处理
mysql -uroot -p
密码
选择你的目标数据库
mysql> use database_name
显示当前字符集
mysql> showvariables like '%char%';
+--------------------------+----------------------------------------+
|Variable_name | Value |
+--------------------------+----------------------------------------+
|character_set_client | gb2312 |
|character_set_connection | gb2312 |
|character_set_database | gb2312 |
|character_set_results | gb2312 |
|character_set_server | gb2312 |
|character_set_system | utf8 |
|character_sets_dir |/usr/local/mysql/share/mysql/charsets/ |
+--------------------------+----------------------------------------+
7 rows in set (0.00sec)
保持字符集统一,如果你要修改哪个字符集,用set命令,如:
mysql> setcharacter_set_client=gbk;
Query OK, 0 rowsaffected (0.00 sec)
mysql> showvariables like '%char%';
+--------------------------+----------------------------------------+
|Variable_name | Value |
+--------------------------+----------------------------------------+
| character_set_client | gbk |
|character_set_connection | gb2312 |
|character_set_database | gb2312 |
|character_set_results | gb2312 |
|character_set_server | gb2312 |
|character_set_system | utf8 |
|character_sets_dir |/usr/local/mysql/share/mysql/charsets/ |
+--------------------------+----------------------------------------+
改回来:
mysql> setcharacter_set_client=gb2312;
Query OK, 0 rowsaffected (0.00 sec)
mysql> showvariables like '%char%';
+--------------------------+----------------------------------------+
|Variable_name | Value |
+--------------------------+----------------------------------------+
|character_set_client | gb2312 |
|character_set_connection | gb2312 |
|character_set_database | gb2312 |
|character_set_results | gb2312 |
|character_set_server | gb2312 |
|character_set_system | utf8 |
|character_sets_dir |/usr/local/mysql/share/mysql/charsets/ |
+--------------------------+----------------------------------------+
需要引起注意的是,项目是什么编码格式就要set成什么编码格式,如果服务器与项目编码不一致,也可能造成编码乱码,所以必须注意要编码一致
其次,如果项目编码跟服务器编码一致,且页面编码全部一致,数据库编码也一致,还是乱码,或者中文变?号,请检查连接编码,并且设置与上述编码一致
比如mysql连接设置:
private static final String className="com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://112.124.111.3:3306/MySQLConnection??useUnicode=true&characterEncoding=utf8" ;
private static final String username = "root";
private static final String password = "password";
这样就可以从根本上解决乱码问题了~