Amazon

Tuesday, October 6, 2009

Storing Multicountry character sets in DB - ISO-8599-1, UTF-8 ETC

Use the function below to store the String or value in DB in Encoded form.

void encodeStringInPstmt(PreparedStatement pstmt, int index, String st) throws IPHException{
if (st== null ){
st= "" ;
}
InputStream inp = new ByteArrayInputStream(st.getBytes());

Reader reader = null ;

try {
//Correct encoding type need to be set before storing in DB. No need to change the DB field datatype from Varchar2 to NVarchar2.
reader = new BufferedReader( new InputStreamReader(inp, "UTF-8" ));
pstmt.setCharacterStream(index, reader, st.length());

} catch (UnsupportedEncodingException e) {
log .fatal( "encodeStringInPstmt() | UnsupportedEncodingException = " +e);
} catch (SQLException s){
log .fatal( "encodeStringInPstmt() | SQLException = " +s);
}
}


This function converts the encoding type of the value to be printed on JSP. The value retrieved from DB, which was stored using function above. The value need to be converted to correct encoding type before printing on JSP. Don't forget to set the encoding type of JPS to UTF-8.

public static final String utf8Convert(String utf8String) throws java.io.UnsupportedEncodingException {

if (utf8String== null ){
utf8String = "" ;
}
byte [] bytes = new byte [utf8String.length()];
for ( int i = 0; i < utf8String.length(); i++) {
bytes[i] = ( byte ) utf8String.charAt(i);
}

String outputString = new String(bytes, "UTF-8" );
return outputString;
}

No comments:

Post a Comment

Amazon Best Sellors

TOGAF 9.2 - STUDY [ The Open Group Architecture Framework ] - Chap 01 - Introduction

100 Feet View of TOGAF  What is Enterprise? Collection of Organization that has common set of Goals. Enterprise has People - organized by co...