Home > Database > Mysql Tutorial > How to Fix 'Incorrect string value' Errors When Inserting UTF-8 Data into MySQL via JDBC?

How to Fix 'Incorrect string value' Errors When Inserting UTF-8 Data into MySQL via JDBC?

DDD
Release: 2024-12-30 11:59:10
Original
209 people have browsed it

How to Fix

Handling Incorrect String Values When Inserting UTF-8 into MySQL via JDBC

When attempting to insert UTF-8 data into a MySQL database using JDBC, you may encounter the error message, "Incorrect string value: 'xF0x90x8Dx83xF0x90...'" This error often occurs when the inserted text contains characters that cannot be represented in MySQL's utf8 character set.

While your connection settings include the use of Unicode ("useUnicode=true") and UTF-8 encoding ("characterEncoding=utf-8"), MySQL's utf8 encoding only supports Unicode characters that can be represented with 3 bytes in UTF-8. The character causing the error, however, requires 4 bytes.

Solution:

To resolve this issue, you have two options:

  • Change the Column Encoding to utf8mb4:
    If your MySQL version is 5.5 or later, you can change the column encoding for the affected column from utf8 to utf8mb4. This encoding allows storage of characters that occupy 4 bytes in UTF-8.
  • Modify Server Configuration:
    Additionally, you may need to set the server property character_set_server to utf8mb4 in your MySQL configuration file. This ensures that MySQL supports 4-byte UTF-8 character sets by default.

Note that Connector/J, commonly used for JDBC connections with MySQL, defaults to 3-byte Unicode. Therefore, it's recommended to leave characterEncoding out of your connection string and configure the MySQL server with character_set_server=utf8mb4 to allow Connector/J to autodetect the UTF-8 setting.

The above is the detailed content of How to Fix 'Incorrect string value' Errors When Inserting UTF-8 Data into MySQL via JDBC?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template