先查下数据库的编码
mysql -uroot -p
>show variables like 'character%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | latin1 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
从以上信息可知数据库的编码为latin1,需要修改为gbk或者是utf8;
其中,character_set_client为客户端编码方式;character_set_connection为建立连接使用的编码;character_set_database数据库的编码;
character_set_results结果集的编码;
character_set_server数据库服务器的编码;
只要保证以上四个采用的编码方式一样,就不会出现乱码问题。
另一个查看数据库编码的命令:
>show variables like ‘collation%’;
停止mysql服务,在ubuntu下使用
sudo service mysql stop
或者
sudo stop mysql
,其他系统下可以用这个
/etc/init.d/mysql stop
修改 /etc/mysql/my.cnf 文件,在[client]下面增加default-character-set=utf8,在[mysqld]下面增加character-set-server = utf8,在[mysql]下面增加default-character-set=utf8,保存关闭文件,重启mysql服务,sudo service mysql start或者sudo start mysql或者
/etc/init.d/mysql start。
进入mysql,
mysql -uroot -p
运行这一句,show variables like 'character%';
若它显示
+--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | 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 | | character_sets_dir | /usr/share/mysql/charsets/ | +--------------------------+----------------------------+
修改成功。
然后再创建数据库,在mysql驱动或者orm在连接时都设置charset=utf8。