"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Solve the \\"String value error\\" exception when MySQL inserts Emoji

Solve the \\"String value error\\" exception when MySQL inserts Emoji

Posted on 2025-04-19
Browse:271

How to Fix \

Resolving Incorrect String Value Exception When Inserting Emoji

When attempting to insert a string containing emoji characters into a MySQL database using JDBC, you may encounter the following exception:

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

This error arises because MySQL's default utf8 character set only supports characters within the Basic Multilingual Plane. To resolve this issue, you need to enable support for the utf8mb4 character set, which extends utf8 to cover the extended plane where emoji characters reside.

Connection Initialization

Set the connection encoding to utf8mb4 immediately after establishing the connection:

DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "username", "password").prepareStatement("SET NAMES 'utf8mb4'");

Database and Table Modifications

Update the character set and collation of your database and affected tables to utf8mb4:

ALTER DATABASE `database` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE `table_name` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

Java Code

Ensure that your Java code is using the utf8mb4 charset for string character encoding. For example, with Connector/J:

DriverManager.getConnection("jdbc:mysql://localhost:3306/database?characterEncoding=utf8mb4", "username", "password");
// ...
preparedStatement.setString(1, "walmart obama ?"); // Emoji characters should be supported now

By following these steps, you can enable support for utf8mb4 and resolve the incorrect string value exception when inserting emoji characters into your MySQL database.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3