gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:23:39 27 4
gpt4 key购买 nike

我有以下字符串值:“walmart obama 👽💔”

我正在使用 MySQL 和 Java。

我收到以下异常:`java.sql.SQLException:不正确的字符串值:'\xF0\x9F\x91\xBD\xF0\x9F...'

这是我要插入的变量:

var1 varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL`

我试图插入“walmart obama 👽💔”的 Java 代码是一个 preparedStatement。所以我正在使用 setString() 方法。

看起来问题出在值 👽💔 的编码上。我怎样才能解决这个问题?以前我使用的是 Derby SQL,而值 👽💔 最终变成了两个正方形(我认为这是空字符的表示)

非常感谢所有帮助!

最佳答案

您拥有的是 EXTRATERRESTRIAL ALIEN (U+1F47D)BROKEN HEART (U+1F494)哪个不在基本的多语言平面上。它们甚至不能在 java 中表示为一个字符,"👽💔".length() == 4。它们绝对不是空字符,如果您没有使用支持它们的字体,就会看到方 block 。

MySQL's utf8 only supports basic multilingual plane, and you need to use utf8mb4 instead :

For a supplementary character, utf8 cannot store the character at all, while utf8mb4 requires four bytes to store it. Since utf8 cannot store the character at all, you do not have any supplementary characters in utf8 columns and you need not worry about converting characters or losing data when upgrading utf8 data from older versions of MySQL.

因此,要支持这些字符,您的 MySQL 需要为 5.5+,并且您需要在任何地方使用 utf8mb4。连接编码需要是utf8mb4,字符集需要是utf8mb4,collaction需要是utf8mb4。对于 java,它仍然只是 "utf-8",但 MySQL 需要一个区别。

我不知道您使用的是什么驱动程序,但设置连接字符集的驱动程序不可知方法是发送查询:

SET NAMES 'utf8mb4'

建立连接后。

See also this for Connector/J :

14.14: How can I use 4-byte UTF8, utf8mb4 with Connector/J?

To use 4-byte UTF8 with Connector/J configure the MySQL server with character_set_server=utf8mb4. Connector/J will then use that setting as long as characterEncoding has not been set in the connection string. This is equivalent to autodetection of the character set.

同时调整您的列和数据库:

var1 varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL

同样,您的 MySQL 版本需要相对最新才能支持 utf8mb4。

关于java.sql.SQLException : Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...' 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39889427/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com