在向数据库表中插入中文时一直报错
MySQL的默认编码是Latin1,不支持中文,要支持中文需要把数据库的默认编码修改为gbk或者utf8。
1、需要以root用户身份登陆才可以查看数据库编码方式(以root用户身份登陆的命令为:>mysql -u root –p,之后输入root用户的密码)。
查看数据库的编码方式命令为:
mysql> show variables where Variable_name like '%char%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| 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_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.08 sec)
从以上信息可知数据库的编码为latin1,需要修改为gbk或者是utf8;
其中,character_set_client为客户端编码方式;
character_set_connection为建立连接使用的编码;
character_set_database数据库的编码;
character_set_results结果集的编码;
character_set_server数据库服务器的编码;
只要保证以上四个采用的编码方式一样,就不会出现乱码问题。
mysql> set character_set_database=utf8;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> set character_set_server=utf8;
Query OK, 0 rows affected (0.00 sec) mysql> show variables where Variable_name like '%char%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | utf8 |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.01 sec)
注意:需要将数据库删除后重新建立才可以生效
mysql> drop database test;
Query OK, 2 rows affected (0.04 sec) mysql> create database test;
Query OK, 1 row affected (0.00 sec) mysql> use test;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A Database changed
插入数据库再查看就可以存入中文了
mysql> select * from dataCenter;
+--------------+----------------+-------------------+-------------------+---------------------+-----------------+
| dataCenterId | dataCenterName | dataCenterAddress | dataCenterLinkman | dataCenterTelephone | dataCenterEmail |
+--------------+----------------+-------------------+-------------------+---------------------+-----------------+
| 1 | 啊 | | | | |
+--------------+----------------+-------------------+-------------------+---------------------+-----------------+
1 row in set (0.00 sec)