Solve the problem of MySQL adding data to the table and inserting Chinese garbled characters


foreword

The Chinese garbled problem occurs when adding data to the table after creating a table using MySQL on the command line. The MySQL version I installed is MySQL 5.7. This problem will not occur after MySQL 8.0, so this is based on the MySQL 5.7 version. Speaking

mysql> insert into student values(1002,'张三');
ERROR 1366 (HY000): Incorrect string value: '\xD5\xC5\xC8\xFD' for column 'name' at row 1

1. Why does this ERROR occur?

This is due to the fact that the default character set in MySQL is Latin1. When we use Chinese to add it to the table, Chinese garbled characters will appear, resulting in an error and ERROR
Picture instanceMySQL
Picture instanceMySQL

2. Solution steps

1: View encoding commands

Use the following command on the command line

show variables like 'character_%';
show variables like 'collation_%';

MySQL instance

2. Modify the my.ini configuration file in the MySQL data directory

To modify the configuration file, use an advanced text editor. I am using Sublime Text 3 here. After opening and modifying with software such as Notepad, the file encoding may be changed to "including BOM header", and the service restart will fail.

default-character-set=utf8 #默认字符集
[mysqld] # 大概在76行左右,在其下添加
...
character-set-server=utf8
collation-server=utf8_general_ci

MySQL example

3. Restart the MySQL service

Here you can manually close or use the command line to restart the MySQL service, the following figure is to use the command line to restart the MySQL serviceMySQL example

4. Review the encoding command again

Continue to use the following commands on the command line

show variables like 'character_%';
show variables like 'collation_%';

MySQL example

5. Add Chinese data to the table again

Notice

Please note here that the character set of the previously created table is Latin1, so ERROR will be reported when adding Chinese. The solution here is to directly delete the database and recreate the library. The default is utf8.
MySQL example

recreate the database

MySQL example

Add Chinese data to the table after recreating the table

MySQL example


Summarize

The above is to solve the problem of MySQL adding data to the table and inserting Chinese garbled characters. It is only for MySQL 5.7 version. The default character set of MySQL 8.0 version is utf8, and Chinese data can be directly inserted into the table. The principle is still the default way to modify the character set, the utf8 character set.
If you forget to modify the default encoding, there will be garbled characters. Starting from MySQL 8.0, the default encoding of the database is changed to utf8mb4, thus avoiding the above-mentioned garbled problem.

Guess you like

Origin blog.csdn.net/cyaya6/article/details/125786006