如何使用latin1中编码的ResultSet对UTF-8中的字符串进行编码 [英] How to encode a string in UTF-8 from a ResultSet encoded in latin1

查看:132
本文介绍了如何使用latin1中编码的ResultSet对UTF-8中的字符串进行编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个需要读/写外部应用程序的第二个数据库的应用程序(使用UTF-8)(使用ISO-8859-1)。



< pre class =lang-java prettyprint-override> try {
// latin1中的数据
String s = rs.getString(sAddrNameF);
System.out.println(s); //显示Adresse d'exp dition
byte [] data = s.getBytes();
String value = new String(data,UTF-8);
System.out.println(UTF8中的数据:+值);
//预期结果应为Adresse d'expédition
} catch(UnsupportedEncodingException e){
e.printStackTrace();
}

此代码无效,我还需要进行相反的转换(写作)在数据库上)。如果有人知道在同一个应用程序中处理不同编码的优雅解决方案,请告诉我,我很感激。

解决方案

  String s = rs.getString(sAddrNameF); 
System.out.println(s); //显示Adresse d'exp dition

这意味着该字符串已损坏数据库,或者您使用错误的编码连接到数据库(例如使用MySQL传递 characterEncoding = utf8 )。



没有将String从一种编码转换为另一种编码的事情。一旦你有一个 String 它总是UTF-16。



如果它只是一个配置问题,你就不会需要担心。 rs.getString()将返回正确的字符串, PreparedStatement.setString()将确保正确保存字符串数据库。



你应该了解的内容Unicode


I'm writing an application (uses UTF-8) that need read/write to a second database of an external application (uses ISO-8859-1).

try {
    // data in latin1
    String s = rs.getString("sAddrNameF");
    System.out.println(s); // shows "Adresse d'exp�dition"
    byte[] data = s.getBytes();
    String value = new String(data, "UTF-8");
    System.out.println("data in UTF8: " + value);
    // The expected result should be "Adresse d'expédition"
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

This code is not working, I also still need do the opposite conversion (writing on the database). If anybody know an elegant solution to dealing with different encoding in the same application please let me know, I appreciate it.

解决方案

String s = rs.getString("sAddrNameF");
System.out.println(s); // shows "Adresse d'exp�dition"

This means that the string is either already corrupted in the database, or you're connecting to the database with the wrong encoding (such as passing characterEncoding=utf8 with MySQL).

There's no such a thing as converting String from one encoding to another. Once you have a String it's always UTF-16.

If it's just a configuration problem, you don't need to worry. The rs.getString() will return proper Strings and PreparedStatement.setString() will make sure Strings are properly saved in the database.

What you should know about Unicode

这篇关于如何使用latin1中编码的ResultSet对UTF-8中的字符串进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆