Unicode文字のストリーム機能を利用してデータの更新を行うプログラム例について説明します。
以下のサンプルアプリケーションでは、ネーミングサービスを起動しているホスト名に、“myhost”を指定しています。サンプルアプリケーションを実行する環境に合わせて、ホスト名の値を修正してください。
また、“OrgData.txt”というファイルのデータをデータベースに追加しています。サンプルアプリケーション実行時に、サンプルアプリケーションのclassファイルと同じフォルダ内に“OrgData.txt”を格納してください。“OrgData.txt”の内容については、以下を参照してください。
テスト名前
// 以下のパッケージをインポートします。 import java.util.*; import java.sql.*; import javax.sql.*; import java.io.*; import javax.naming.*; // クラスを定義します。 public class MyUnicode { public static void main(String args[]) { try{ // JNDI環境を指定します。 Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.fujitsu.symfoware.jdbc2.jndisp.SYMContextFactory"); env.put(Context.PROVIDER_URL,"SYM://myhost:26600"); InitialContext ctx = new InitialContext(env); // JDBCデータソースを取得します。 DataSource ds = (DataSource)ctx.lookup("jdbc/ds1"); // データベースと接続します。 Connection con = ds.getConnection(); // 自動コミットモードの無効化 con.setAutoCommit(false); // データ削除 Statement stmt = con.createStatement(); stmt.executeUpdate("DELETE FROM GENERAL.EMPLOYEE"); stmt.close(); // INSERT文を準備 PreparedStatement pstmt = con.prepareStatement("INSERT INTO GENERAL.EMPLOYEE VALUES(1, ?)"); // Unicodeデータを設定 FileReader fr = new FileReader("OrgData.txt"); pstmt.setCharacterStream(1, fr); // INSERT文を実行 pstmt.executeUpdate(); pstmt.close(); fr.close(); con.commit(); // ResultSetインタフェースのオブジェクトを生成 Statement stmt2 = con.createStatement(); ResultSet rs = stmt2.executeQuery("SELECT NAME FROM GENERAL.EMPLOYEE"); // データベースのデータを参照 while (rs.next()) { Reader rd = rs.getCharacterStream(1); // 出力先ファイルを指定 Writer wr = new FileWriter("AftData.txt"); // ストリームからデータをchar配列で一括に読み込み char[] buff = new char[10]; rd.read(buff); // 出力先ファイルにデータを印字 wr.write(buff); wr.close(); rd.close(); } // 解放処理 rs.close(); stmt2.close(); con.commit(); con.close(); } // SQLExceptionが発生した場合の処理を記述します。 catch (SQLException e) { // エラー情報を出力します。 System.out.println("ERROR MESSAGE : " + e.getMessage()); System.out.println("SQLSTATE : " + e.getSQLState()); System.out.println("ERROR CODE : " + e.getErrorCode()); e.printStackTrace(); } // その他のExceptionが発生した場合の処理を記述します。 catch (Exception e) { // スタックトレースを出力します。 System.out.println("ERROR MESSAGE : " + e.getMessage()); e.printStackTrace(); } } }