Get the App
SLTechnology News&Howtos  ›  Database  › 

The reason why UTF-8 coding can not be used in MySQL

Shulou Source: shulou.com Published: 2022-06-01 18:13:36 10月02日 Update

Let's learn about the reasons why UTF-8 coding can not be used in MySQL. I believe you will benefit a lot after reading it. The text is not very good. I hope you can't use UTF-8 coding in MySQL. This short article is what you want.

UTF-8 coding method of MySQL

MySQL has supported UTF-8 since version 4.1, that is, in 2003, but the current popular UTF-8 standard (RFC 3629) was specified after that. Because of this, the UTF-8 in MySQL is inconsistent with the UTF-8 in our daily development, which leads to some problems. MySQL's UTF-8 only supports a maximum of three bytes per character, while the real UTF-8 is a maximum of four bytes per character.

Problem recurrence

The database table is as follows: utf8 coding method

Deposit a record in the database:

@ Test public void testInsert () {User user = new User (); user.setUsername ("\ uD83D\ uDE00"); user.setPassword ("123456"); userRepo.save (user);}

Here is only part of the code, do not understand it does not matter, here is to insert a record to the user table. Where username is\ uD83D\ uDE00.

Actually,\ uD83D\ uDE00 is an emoji expression.

Because the utf8 character set in MySQL only supports the three-byte UTF-8-encoded Unicode range, and the emoji characters belong to the four-byte encoding part, the program is expected to run in error. Run this code:

As expected, the report was wrong.

Solve the problem

Although MySQL's UTF-8 is flawed, MySQL (including mariadb) officials did not fix the bug, but supported the real UTF-8 through the rerelease of "utf8mb4" in 2010. So to solve this problem, you can only set the MySQL database to the utf8mb4 character set.

Summary

This problem was also discovered because an emoji emoji was saved when the data was saved. In fact, when I first started using MySQL, I found a utf8mb4, but I didn't know the difference between UTF8 and UTF8MB4. From this lesson, use MySQL to honestly set the character set to utf8mb4 in the future.

After reading this article on the reasons why you can't use UTF-8 coding in MySQL, many readers will want to know more about it. For more industry information, you can follow our industry information section.

Tags: UTF-8 coding character mode problem byte data support reason consistency code content character set database time more industry emoji part sure Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Linux Huawei macOS Docker