如何删除MySQL中不适合utf8编码的坏字符?


问题内容

我有脏数据。有时它包含像字符这样。我使用这些数据进行查询

WHERE a.address IN ('mydatahere')

对于这个角色我得到

org.hibernate.exception.GenericJDBCException:操作’IN’的排序规则(utf8_bin,IMPLICIT),(utf8mb4_general_ci,COERCIBLE),(utf8mb4_general_ci,COERCIBLE)的非法混合

如何过滤出这样的字符?我使用Java。

谢谢。


问题答案:

可能这会像帮助我一样帮助某人。

public static String removeBadChars(String s) {
  if (s == null) return null;
  StringBuilder sb = new StringBuilder();
  for(int i=0;i<s.length();i++){ 
    if (Character.isHighSurrogate(s.charAt(i))) continue;
    sb.append(s.charAt(i));
  }
  return sb.toString();
}