In recent years, MySQL database has become the database management system of choice for many companies, especially in the Internet field, and its frequency of use can even be said to be staggeringly high. However, even a top-level database like MySQL cannot avoid inexplicable problems. One of the common problems is the problem of garbled Chinese characters.
The Chinese character garbled problem means that after we import the data storing Chinese characters into the MySQL database, when we open the relevant web page or query the relevant data, the Chinese characters displayed on the page are garbled, causing the entire page or data to be garbled. Readability is greatly reduced.
The root cause of this problem is that the default character set used by the MySQL database is Latin1 instead of UTF-8. As a result, the Chinese characters in the imported text file cannot be correctly converted into UTF-8 encoding.
So, how to solve the problem of garbled Chinese characters in MySQL? The following are some solutions:
In the MySQL configuration file my.cnf, find [client] and [mysqld] Two parts, and modify the character set to utf8mb4. For example:
[client]
default-character-set=utf8mb4
[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
After restarting the MySQL service, all data tables and data will use the utf8mb4 character set.
Use the "set names 'utf8'" command before performing database operations Set the character encoding of MySQL to UTF-8, for example:
mysql> set names 'utf8';
This operation will allow the data in subsequent SQL statements to be correctly converted to UTF-8 Encoding to avoid garbled characters.
When connecting to the MySQL database, manually specify the character set in the configuration item. For example, when using PHP to connect to MySQL, you can use the following code:
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysqli_set_charset($conn, "utf8" );
Manually specifying the character set can ensure that the MySQL database can correctly convert it into the target character set when reading data, avoiding garbled characters.
To sum up, to solve the problem of garbled Chinese characters in MySQL, we can use many methods. When the MySQL default character set is not UTF-8, changing the default character set to UTF-8 is the most thorough solution. In addition, we can also reset the character set before importing data, or manually specify the character set in the code to avoid the problem of MySQL displaying garbled Chinese characters, thereby ensuring the readability and accuracy of the data.
The above is the detailed content of How to solve mysql Chinese character garbled characters. For more information, please follow other related articles on the PHP Chinese website!