这篇文章主要介绍“怎么解决MySQL命令窗口中文乱码或插入中文数据失败的问题”,在日常操作中,相信很多人在怎么解决MySQL命令窗口中文乱码或插入中文数据失败的问题问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么解决MySQL命令窗口中文乱码或插入中文数据失败的问题”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
在Windwos上使用命令窗口操作MySQL数据库时,如果命令窗口的字符编码与数据库不一致时,就会出现中文乱码的情况
比如查询会出现中文乱码,或者插入数据会出现错误“ERROR 1366 (HY000): Incorrect string value: '\xD5\xC5\xC8\xFD' for column 'name' at row 1”
mysql> insert into user(name,gender,age) values('张三','男',22);
ERROR 1366 (HY000): Incorrect string value: '\xD5\xC5\xC8\xFD' for column 'name' at row 1
mysql> select * from user;
+----+----------+--------+-----+---------------------+| id | name | gender | age | updated_time |
+----+----------+--------+-----+---------------------+| 1 | zhangsan | M | 22 | 2018-10-31 17:03:25 |
| 2 | 寮犱笁 | 鐢? | 22 | 2018-11-01 09:01:43 |
+----+----------+--------+-----+---------------------+2 rows in set (0.00 sec)
这时可以先查看下环境编码配置,我的是utf8,结果是下面这样
mysql> show variables like 'char%';
+--------------------------+---------------------------------------------------------+| 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 | C:\Program Files\MySQL\MySQL Server 5.5\share\charsets\ |
+--------------------------+---------------------------------------------------------+8 rows in set (0.00 sec)
查看windwos命令窗口的的属性可知,编码格式为GBK且不能更改
这时我们可以使用“set names gbk;”来指定客户端发送给mysql语句时的编码格式,并且可以看到client、connection、results三个变量的编码格式变为了gbk,其它的没有变化
mysql> set names gbk;
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like 'char%';
+--------------------------+---------------------------------------------------------+| Variable_name | Value |
+--------------------------+---------------------------------------------------------+| character_set_client | gbk |
| character_set_connection | gbk |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | gbk |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | C:\Program Files\MySQL\MySQL Server 5.5\share\charsets\ |
+--------------------------+---------------------------------------------------------+8 rows in set (0.00 sec)
再次执行下插入操作没问题了,查询数据中文也不会乱码了
mysql> insert into user(name,gender,age) values('张三','男',22);
Query OK, 1 row affected (0.04 sec)
mysql> select * from user;
+----+----------+--------+-----+---------------------+| id | name | gender | age | updated_time |
+----+----------+--------+-----+---------------------+| 1 | zhangsan | M | 22 | 2018-10-31 17:03:25 |
| 2 | 张三 | 男 | 22 | 2018-11-01 09:01:43 |
+----+----------+--------+-----+---------------------+2 rows in set (0.00 sec)
到此,关于“怎么解决MySQL命令窗口中文乱码或插入中文数据失败的问题”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!