博主由于是做服务器开发的,就打算自学mysql数据库。因此就在shell端安装mysql
安装命令:sudo apt-get install mysql-server mysql-client
sudo apt-get install php5-mysql
安装之后进行插入中文操作的时候出现
- mysql> select * from worker;
- +----+------+----------------+------+
- | id | name | address |level |
- +----+------+----------------+------+
- | 1 | ?? | ????????????? | 0 |
- | 2 | ??? | ?????????????? | 1 |
- | 3 | jack | shanghai | 1 |
- +----+------+----------------+------+
下面进入正题
1、首先确定server、数据库和表的默认字符级
- mysql> show variables like 'character_set_%';
- +--------------------------+----------------------------+
- | 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/ |
- +--------------------------+----------------------------+
- 8 rows in set (0.00 sec)
2、通过上面的查询结果,我们知道server和database默认字符集为拉丁文latin1,表毫无疑问是采用server字符集作为默认字符集。这样就导致了,我们通过sql脚本插入中文时乱码的问题。由于我们代码中统一采用了UTF-8作为工程的默认字符集编码,为了统一,我们这里需要将字符集修改为UTF-8。
修改mysql的配置文件
sudo vi /etc/mysql/my.cnf
在[client]的下方加入如下语句:
no-auto-rehash
default-character-set=utf8
在[mysqld]下加入
socket = /var/run/mysqld/mysqld.sock
port = 3306
character-set-server=utf8 等内容,自行对比,有的就不用加了,一般只需要加入 character-set-server=utf8.
这时候shell 进入mysql,执行mysql>:show variables like 'character%' , 结果如图:
4、最后重新启动mysql,重启命令:sudo /etc/init.d/mysql restart,然后再进行插入中文操作,问题完美解决
mysql> select * from worker;
+------+------+--------------+--------+-------+
| id | name | address | salary | level |
+------+------+--------------+--------+-------+
| 100 | tomo | 上海 | 3000 | 0 |
| 101 | jack | 浦东新区 | 6000 | 1 |
| 102 | jack | 徐汇区 | 6000 | 1 |
+------+------+--------------+--------+-------+