【发布时间】:2019-06-28 04:04:34
【问题描述】:
我使用 MySQL 5.7,我有一个表,其中有一列使用“utf8”字符集。不幸的是,它不是 utf8mb4,因此当我的应用尝试插入超出“utf8”范围的字符(例如表情符号)时,我总是会收到错误消息。
很遗憾,我不能很快将字符集更改为“utf8mb4”,所以我想知道是否有可能在将错误插入表格之前检测到那些导致错误发生的字符,并让我们的客户知道他们不能使用它们。
我在某处读到 U+0000 到 U+FFFF 范围之外的任何内容都会导致错误发生。我的应用程序是在 Java 8 中实现的。所以,我的问题是:如何编写可以从 String 实例中找到此类有问题的字符的代码? the following code 做我想做的事吗?
import java.util.Set;
import java.util.stream.Collectors;
class Utf8Mb3Validator {
/**
* finds characters which can’t be stored in a MySQL “utf8” column out of a given String.
*
* @param input a String which you want to check
* @return a Set which contains strings that can't be inserted into MySQL "utf8" columns
*/
Set<String> findProblematicStrings(String input) {
// References:
// https://dev.mysql.com/doc/refman/5.7/en/charset-unicode-utf8mb3.html
// https://www.oracle.com/technetwork/java/javase/downloads/supplementary-142654.html?printOnly=1
// https://stackoverflow.com/q/56800767/3591946
return input
.codePoints() // get Unicode code points
.filter(codePoint -> Character.charCount(codePoint) > 1) // search for non-BMP characters
.mapToObj(codePoint -> new String(Character.toChars(codePoint))) // convert code points into Strings
.collect(Collectors.toSet());
}
}
我也把这个问题发到了 MySQL 论坛:https://forums.mysql.com/read.php?39,675862,675862#msg-675862
【问题讨论】:
-
谢谢,我刚刚看完了。使用 if(Character.charCount(codePoint) == 1) 迭代 String#codePoints() 的返回值似乎是一种解决方案。