How to encode a string in UTF-8 from a ResultSet encoded in latin1

℡╲_俬逩灬. 提交于 2019-12-02 01:14:19
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

We need to mension string as StandardCharsets.UTF_8

try {
        // data in latin1
        String s = rs.getString("sAddrNameF");
        System.out.println(s); // shows "Adresse d'exp�dition"
        byte[] data = rs.getBytes("sAddrNameF");
        String value = new String(data, StandardCharsets.UTF_8);
        System.out.println("data in UTF8: " + value);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

String value = new String(data,"ISO-8859-1");

The function getBytes takes also a Charset or just string with the desired encoding.

byte[] data = s.getBytes("UTF-8");
// or
byte[] data = s.getBytes(Charset.forName("UTF-8"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!