在Ubuntu下安装了MySQL数据库,为了便于使用,欲将字符集统一设置为utf8,而不是默认的latin1。
进入mysql,输入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 | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
在网上查询到以下解决办法方法:
修改mysql的启动配置文件my.cnf:
找到[client] 添加:
default-character-set=utf8
找到[mysqld] 添加:
default-character-set=utf8
init_connect='SET NAMES utf8'
然后重启mysql服务。
可是我根据这样修改后启动mysql服务报错,启动不了。在网上试了多种解决办法,最后找到一个方法,可以解决,如下:
其他的还跟上面一样,只有在[mysqld]下面添加的
default-character-set=utf8
改为:
character-set-server=utf8
输入命令sudo service mysql restart重新启动mysql,启动成功!再查看编码为:
+--------------------------+----------------------------+
| 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/ |
+--------------------------+----------------------------+
问题解决,表中中文数据不再乱码。
提示:my.cnf文件通常位于 /etc/mysql/ 或 /etc/ 下,可能因安装版本或系统而异。