【问题标题】:Insert non-English string into UTF-8 Oracle database将非英文字符串插入 UTF-8 Oracle 数据库
【发布时间】:2013-04-10 15:19:05
【问题描述】:

我有一个 Oracle,它的编码是 UTF-8。当我在其中插入一些非英语字符串时,我会得到 ORA-12899。我认为原因是一些非英语在 UTF-8 系统中需要 3 个字节。

最简单的解决方案是延长Oracle的长度。我想修剪字符串,但找不到修剪字符串的单一解决方案。有什么建议吗?我试图获取字节长度,但该值不适用于 UTF-8。

【问题讨论】:

  • 列是哪种数据类型?此外,对于长度,请尝试LENGTHB(以字节为单位)而不是LENGTH(以字符为单位)。
  • 如果您想做与@EgorSkriptunoff 的回答相同的事情,但在Java 中,请参阅stackoverflow.com/questions/2726071/…

标签: java oracle utf-8 eclipselink


【解决方案1】:

使用lengthb() 获取字节长度。截断你的字符串,直到它适合列:

while lengthb(x) > column_length_in_bytes loop
  x := substr(x, 1, length(x)-1);
end loop;

【讨论】:

    【解决方案2】:
    public static String truncatedUTF8( String input, int maxBytesInUTF8 ) {
        if( input.length() * 4 <= maxBytesInUTF8 ) {
            return input;
        }
        int max = 0, i;
        boolean lastSurrogate = false;
        for( i = 0; i < input.length() && max <= maxBytesInUTF8; ++i ) {
            int cc = Character.codePointAt(input, i);
            lastSurrogate = false;
            if (cc <= 0x7F) {
                max++; 
            } else if (cc <= 0x7FF) {
                max += 2; 
            } else if (cc <= 0xFFFF) {
                max += 3;
            } else if (cc <= 0x10FFFF) {
                lastSurrogate = true;
                max += 4;
                i++;
            }    
        }
    
        if( max < maxBytesInUTF8 ) {
            return input;
        }
        if( max > maxBytesInUTF8) {
            i--;
            if( lastSurrogate ) i--;
        }
    
        if( i - 1 >= input.length() && 
            !Character.isSurrogatePair(input.charAt(i-2), input.charAt(i-1)) &&
            Character.isSurrogate(input.charAt(i-1))) {
            i--;
        }
    
        return input.substring(0, i);
    }
    
    System.out.println(truncatedUTF8("äää", 5));
    //"ää" because "äää" takes 6 bytes and "ää" takes 4
    

    【讨论】:

      猜你喜欢
      • 2013-05-05
      • 2018-09-14
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      相关资源
      最近更新 更多