我有脏数据。有时它包含像 this 这样的字符.我使用这些数据进行查询,例如
WHERE a.address IN ('mydatahere')
对于这个角色,我得到了
org.hibernate.exception.GenericJDBCException: Illegal mix of collations (utf8_bin,IMPLICIT), (utf8mb4_general_ci,COERCIBLE), (utf8mb4_general_ci,COERCIBLE) for operation ' IN '
如何过滤掉这样的字符?我使用 Java。
谢谢。
最佳答案
当我遇到这样的问题时,我使用 Perl 脚本来确保通过使用如下代码将数据转换为有效的 UTF-8:
use Encode;
binmode(STDOUT, ":utf8");
while (<>) {
print Encode::decode('UTF-8', $_);
}
此脚本在 stdin
上采用(可能已损坏)UTF-8 并将有效的 UTF-8 重新打印到 stdout
。无效字符替换为 �
(U+FFFD
, Unicode replacement character)。
如果您在良好的 UTF-8 输入上运行此脚本,则输出应与输入相同。
如果您在数据库中有数据,使用 DBI 扫描您的表并使用这种方法清理所有数据以确保所有内容都是有效的 UTF-8 是有意义的。
这是同一脚本的 Perl 单行版本:
perl -MEncode -e "binmode STDOUT,':utf8';while(<>){print Encode::decode 'UTF-8',\$_}" < bad.txt > good.txt
编辑:添加了仅限 Java 的解决方案。
这是一个如何在 Java 中执行此操作的示例:
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
public class UtfFix {
public static void main(String[] args) throws InterruptedException, CharacterCodingException {
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPLACE);
decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
ByteBuffer bb = ByteBuffer.wrap(new byte[] {
(byte) 0xD0, (byte) 0x9F, // 'П'
(byte) 0xD1, (byte) 0x80, // 'р'
(byte) 0xD0, // corrupted UTF-8, was 'и'
(byte) 0xD0, (byte) 0xB2, // 'в'
(byte) 0xD0, (byte) 0xB5, // 'е'
(byte) 0xD1, (byte) 0x82 // 'т'
});
CharBuffer parsed = decoder.decode(bb);
System.out.println(parsed);
// this prints: Пр?вет
}
}
关于java - mysql如何去除不适合utf8编码的坏字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13657019/