精华区 [关闭][返回]

当前位置:网易精华区>>讨论区精华>>编程开发>>● Java>>JAVA编程>>数据库接口>>数据库中处理中文的一种解决方案

主题:数据库中处理中文的一种解决方案
发信人: wan1976(八十年代)
整理人: zjxyz(2002-12-19 11:15:50), 站内信件
转载自apusic

    数据库中一般存放的是native code字符串,而Java中处理的都是Unicode字符串,可以在Java中对字符串的原始Unicode码进行BASE64编码存到数据库里,取出来的时候进行BASE64解码恢复成Unicode字符串,这样存在数据库里的始终是7位ASCII码,但表示的是16位Unicode码。注意这里不能用UTF-8编码,因为UTF-8是8位的,存到数据库里可能会有问题。采用这种方案也有一些问题,一是数据的长度增加了,占用更多的空间,还有就是不能用sqlplus等工具直接修改数据库。 

import sun.misc.BASE64Encoder; 
import sun.misc.BASE64Decoder; 

public class EncDec 

    static BASE64Encoder encoder = new BASE64Encoder(); 
    static BASE64Decoder decoder = new BASE64Decoder(); 

    public static String encode(String input) { 
        char[] chars = input.getChars(); 
        byte[] bytes = new byte[chars.length*2]; 
        for (int i = 0; i < chars.length; i++) {
            bytes[i*2] = (byte)((chars[i] >> 8) & 0xff); 
            bytes[i*2+1] = (byte)(chars[i] & 0xff); 
        } 
        return encoder.encode(bytes); 
    } 
  
    public static String decode(String input) { 
        byte[] bytes = decoder.decode(input); 
        char[] chars = new char[bytes.length/2]; 
        for (int i = 0; i < chars.length; i++) {
            chars[i] = (char)(((bytes[i*2] & 0xff) << 8) + (bytes[i*2+1] & 0xff));
        }
        return new String(chars);
    }
} 


[关闭][返回]