I. 取中文 用 JDBC 执行 SELECT 语句从服务器端读取数据(中文)后,将数据用 APPEND 方法加到 TextArea(TA) ,不能正确显示。但加到 List 中时,大部分汉字却可正确显示。 将数据按“ISO-8859-1” 编码方式转化为字节数组,再按系统缺省编码方式 (Default Character Encoding) 转化为 STRING ,即可在 TA 和 List 中正确显示。 程序段如下: dbstr2 = results.getString(1); //After reading the result from DB server,converting it to string. dbbyte1 = dbstr2.getBytes(“iso-8859-1”); dbstr1 = new String(dbbyte1); 在转换字符串时不采用系统默认编码方式,而直接采用“ GBK” 或者 “GB2312” ,在 A 和 B 两种情况下,从数据库取数据都没有问题。 II. 写中文到数据库 处理方式与“取中文”相逆,先将 SQL 语句按系统缺省编码方式转化为字节数组,再按“ISO-8859-1”编码方式转化为 STRING ,最后送去执行,则中文信息可正确写入数据库。 程序段如下: sqlstmt = tf_input.getText(); //Before sending statement to DB server,converting it to sql statement. dbbyte1 = sqlstmt.getBytes(); sqlstmt = newString(dbbyte1,”iso-8859-1”); _stmt = _con.createStatement(); _stmt.executeUpdate(sqlstmt); ……
我写的两个函数,能解决jsp的数据库中文问题可我不知道servlet怎么解决中文问题 //get string from database and change it into chinese public String readChinese(String s) { try { String temp = new String(s.getBytes("GB2312"),"8859_1"); return temp; } catch(Exception e) { return s; } } //write string to the database's chinese transform public static String writeChinese(String s) { char[] orig =s.toCharArray(); byte[] dest =new byte[orig.length]; for(int i=0;i<orig.length;i++) dest[i] =(byte)(orig[i]&0xFF); try { ByteToCharConverter toChar =ByteToCharConverter.getConverter("gb2312"); return new String(toChar.convertAll(dest)); } catch(Exception e) { return s; } }
public String readChinese(String s)
{
try
{
String temp = new String(s.getBytes("GB2312"),"8859_1");
return temp;
}
catch(Exception e)
{
return s;
}
} //write string to the database's chinese transform
public static String writeChinese(String s)
{
char[] orig =s.toCharArray();
byte[] dest =new byte[orig.length];
for(int i=0;i<orig.length;i++)
dest[i] =(byte)(orig[i]&0xFF);
try
{ ByteToCharConverter toChar =ByteToCharConverter.getConverter("gb2312"); return new String(toChar.convertAll(dest));
}
catch(Exception e)
{
return s;
}
}