Amazon

Monday, October 5, 2009

Easy to Play with Unicode Chars

package test.unicode;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class OdbcAccessConnection {
/**
* Method to set convert the String to CharacterStream so that it could be stored in DB with proper
* Unicode Conversion
* @param pstmt
* @param st
* @throws SQLException
*/
static void encodeStringInPstmt(PreparedStatement pstmt, String st) throws SQLException{
InputStream inp = new ByteArrayInputStream(st.getBytes());
Reader reader = new InputStreamReader(inp) ;
pstmt.setCharacterStream(1, reader, st.length());
//Closing the readers
try {
reader.close();
inp.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public static void main(String [] args) {
Connection con = null;
Statement stmt = null;
ResultSet rset = null;
PreparedStatement pstmt = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;

// Connect with a url string
con = DriverManager.getConnection("jdbc:odbc:HY_ACCESS");
System.out.println("Connection ok.");

//String with Unicode ISO-8859-1 unicode characters
String st = "5 && eev ç Ü Ø Å sanj Character À Á 11 Â Ã Ä Å Æ Ç È É Ê Ë Ì Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ø ù ú û ü ý þ ÿ";
pstmt = con.prepareStatement("insert into test (charset) values (?)");
for (long i = 0; i <>
st = i+" && eev ç Ü Ø Å sanj Character À Á 11 Â Ã Ä Å Æ Ç È É Ê Ë Ì Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ø ù ú û ü ý þ ÿ";
encodeStringInPstmt(pstmt, st); //Special treatment to Unicode Char String
pstmt.executeUpdate(); //Storing in table
}
stmt = con.createStatement();
rset = stmt.executeQuery("select * from test");
File f = new File("c:\\sanjeev\\unicode.txt");
//Reading the Unicode string from DB and storing in file.
FileOutputStream fout = new FileOutputStream(f);
while(rset.next()){
String s = new String(rset.getBytes("charset"));//Read in form of Bytes. It will come as it is in DB.
System.out.println(s);
fout.write(s.getBytes());
fout.write('\n');

}
fout.close();

} catch (Exception e) {
System.err.println("Exception: "+e.getMessage());
}
finally{
try {
pstmt.close();
rset.close();
stmt.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
}

No comments:

Post a Comment

Amazon Best Sellors

Weblogic - Server Creation - Issues

Datasource creation using python script.  Python Script was failing after creating Datasource. From UI Admin Console, if I try to activat...