您的位置:首页 > 产品设计 > UI/UE

Mysql插入数据 Incorrect string value: '\xF0\x9F\x98\x84

2017-11-03 21:13 513 查看
不知道什么情况先编辑的全部没有了

错误:不能向mysql插入4个和以上的字符,大多数是表情之类的比如:emoji表情

以前解决:是过滤emoji表情,但emoji表情ios android有些时候不同步,并且后面还有增加的可能,就有了以下解决方案

解决:

1.插入4个以下的

1.1查看unicode 和 utf-8编码对应

// Unicode符号范围 | UTF-8编码方式
// (十六进制) | (二进制)
// --------------------+---------------------------------------------
// 0000 0000-0000 007F | 0xxxxxxx
// 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
// 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
// 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx


1.2过滤掉4个字节以上的字符

public static String fliterFourUnicode(String source) throws UnsupportedEncodingException {
byte[] sourceBytes;

sourceBytes = source.getBytes("utf-8");
int subIndex = 0;
String str = "";
do {
int curByte = Byte.toUnsignedInt(sourceBytes[subIndex]);
if (curByte > 0x00 && curByte <= 0x7f) { //0xxxxxxx
str = str + (char) sourceBytes[subIndex];
subIndex++;
} else if (curByte >= 0xc0 && curByte <= 0xdf) { //110xxxxx
byte[] bytes = { sourceBytes[subIndex], sourceBytes[subIndex + 1] };
str = str + new String(bytes, "utf-8");
subIndex += 2;
} else if (curByte >= 0xe0 && curByte <= 0xef) { //1110xxxx
byte[] bytes = { sourceBytes[subIndex], sourceBytes[subIndex + 1], sourceBytes[subIndex + 2] };
str = str + new String(bytes, "utf-8");
subIndex += 3;
} else if (curByte >= 0xf0 && curByte <= 0xf7) { //11110xxx
str = str + "*";
subIndex += 4;
} else if (curByte >= 0xf8 && curByte <= 0xfb) { //111110xx
str = str + "*";
subIndex += 5;
} else if (curByte >= 0xfc && curByte <= 0xfd) { //1111110x
str = str + "*";
subIndex += 6;
} else if (curByte >= 0xfe) { //11111110
str = str + "*";
subIndex += 7;
} else { //解析失败不是UTF-8编码开头字符
return str + "*";
}

} while (subIndex < sourceBytes.length);
return str;
}
2.让Mysql支持4个以上的,这种方案未测试过

2.1 修改字段类型为 varchar

2.2 修改utf8_general_ci 到utf8mb4_general_ci

2.3 去掉jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&characterEncoding=UTF-8中的&characterEncoding=UTF-8

让他自己适配,也可以升级高版本驱动
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐