gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:53:08 26 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 代码是一个准备好的语句。所以我使用 setString() 方法。

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

非常感谢所有帮助!

最佳答案

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

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,集合需要为 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/37854335/

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