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.
Set the connection encoding to utf8mb4 immediately after establishing the connection:
DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "username", "password").prepareStatement("SET NAMES 'utf8mb4'");
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;
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.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3